TreeSet比较器顺序(Comparator)
1、示例代码如下:
使用匿名内部类:
package com.jh.www;
import java.util.Comparator;
import java.util.TreeSet;
public class Test7 {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();//优先以年龄进行排序;
return num==0 ? s1.getName().compareTo(s2.getName()) :num;//其次以姓名进行排序;
}
});
ts.add(new Student("张三",28));
ts.add(new Student("李四",20));
ts.add(new Student("张三",28));
ts.add(new Student("李四",20));
ts.add(new Student("王五",24));
System.out.println(ts);
}
}