欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

比较器排序TreeSet

程序员文章站 2022-07-09 22:35:44
...
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class Demo04 {
    public static void main(String[] args) {
        Set<Cat1> s = new TreeSet<>(new Comparator<Cat1>() {
            @Override
            public int compare(Cat1 o1, Cat1 o2) {
                if(o1.getName().length() != o2.getName().length())
                    return o1.getName().length() - o2.getName().length();
                else 
                    if(o1.getAge() != o2.getAge())
                        return o1.getAge() - o2.getAge();
                    else 
                       return o1.getName().compareTo(o2.getName());
            }
        });
        s.add(new Cat1("豆包",20));
        s.add(new Cat1("沙包",20));
        s.add(new Cat1("菜鹤包",2));
        s.add(new Cat1("土包",2));
        s.add(new Cat1("大傻包",21));
        s.add(new Cat1("和包",4));
        s.add(new Cat1("豆沙包",2));
        System.out.println("s = " + s);
    }
}

class Cat1 {
    private String name;
    private Integer age;

    public Cat1(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Cat1() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Cat1{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

相关标签: java笔记 java