自定义排序:Comparator & Comparable
Comparable 结合 TreeSet 使用
Student.java
@Data @AllArgsConstructor public class Student implements Comparable<Student>{ private String name; private int age; @Override public int compareTo(Student o) { return this.age > o.age ? 1 : -1; } }
测试:
@Test public void testComparable(){ Student s1 = new Student("abb",12); Student s2 = new Student("aab",15); Student s3 = new Student("cbs",10); TreeSet<Student> treeSet = new TreeSet<>(); Collections.addAll(treeSet,s1,s2,s3); System.out.println(treeSet); }
输出结果:
[Student(name=cbs, age=10), Student(name=abb, age=12), Student(name=aab, age=15)]
自定义排序:Comparator 结合 Collections.sort( ) 使用
MyComparator.java:
@Data @AllArgsConstructor public class MyComparator implements Comparator<Object> { @Override public int compare(Object o1, Object o2) { Teacher t1 = (Teacher) o1; Teacher t2 = (Teacher) o2; if(t1.getAge()>t2.getAge()){ return -1; }else if(t1.getAge()<t2.getAge()){ return 1; }else{ return 0; } } }
Teacher.java:
@Data @AllArgsConstructor public class Teacher { private String name; private int age; }
测试:
@Test public void testComparator(){ Teacher t1 = new Teacher("abb",12); Teacher t2 = new Teacher("aab",15); Teacher t3 = new Teacher("cbs",10); List<Teacher> list = new ArrayList<>(); Collections.addAll(list,t1,t2,t3); System.out.println("排序前: "+list); Collections.sort(list,new MyComparator()); System.out.println("排序后: "+list); }
结果:
排序前: [Teacher(name=abb, age=12), Teacher(name=aab, age=15), Teacher(name=cbs, age=10)] 排序后: [Teacher(name=aab, age=15), Teacher(name=abb, age=12), Teacher(name=cbs, age=10)]
爱来爱去没了反应 灯火惊动不了神经 有时爱情~徒有虚名