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

TreeSet使用比较器Comparator排序

程序员文章站 2022-07-09 22:35:02
...
package myTreeSetDemo;

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
package myTreeSetDemo;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetComparatorDemo {
    public static void main(String[] args) {
    	//使用匿名内部类
        TreeSet<Student> treeSet = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //先比较年龄
                int num = s1.getAge() - s2.getAge();
                //若年龄相等,再比较姓名
                int num2 = (num == 0 ? s1.getName().compareTo(s2.getName()) : num);
                return num2;
            }
        });

        Student s1 = new Student("xiaozhao", 19);
        Student s2 = new Student("xiaoli", 20);
        Student s3 = new Student("xiaowang", 18);
        Student s4 = new Student("xiaoma", 23);

        Student s5 = new Student("xiaohua", 20);
        Student s6 = new Student("xiaohua", 20);

        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        treeSet.add(s4);

        treeSet.add(s5);
        treeSet.add(s6);

        for (Student s : treeSet) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

结果:
TreeSet使用比较器Comparator排序

相关标签: java java