内部比较器
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Comparable<Student> {
private Integer id;
private String name;
@Override
public int compareTo(Student stu) {
return this.getId().compareTo(stu.getId());
}
public static void main(String[] args) {
TreeSet<Student> stu = new TreeSet<>();
Student name2 = new Student(2, "c:yu");
Student name3 = new Student(3, "b:ge");
Student name1 = new Student(1, "a:li");
stu.add(name2);
stu.add(name3);
stu.add(name1);
System.out.println(stu);
}
}
外部比较器
public static void main(String[] args) throws Exception {
TreeSet<User> set = new TreeSet<>(new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return (o1.getAge()+"").compareTo(o2.getAge()+"")==0 ? o1.getName().compareTo(o2.getName()):(o1.getAge()+"").compareTo(o2.getAge()+"") ;
}
});
set.add(new User("zhangsan",28));
set.add(new User("lisi",26));
set.add(new User("wangwu",26));
set.add(new User("chenliu",19));
set.add(new User("chenl",20));
set.add(new User("chen",22));
set.add(new User("xhaoqi",28));
Iterator<User> it = set.iterator();
while(it.hasNext()){
User user = it.next();
//chenliu:19 chenl:20 chen:22 lisi:26 wangwu:26 xhaoqi:28 zhangsan:28
System.out.print(user.getName()+":"+user.getAge()+"\t\t");
}
上面直接在main方法中写了
也可以创建一个比较类
public class ByIdComparable implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.getId().compareTo(o2.getId());
}
}