比较排序comparator的使用
1.比较的带参构造方法使用的是对象元素进行排序。
2.比较排序器就是让集合构造方法接收comparator的实现类对象,重写compare(T t1,T t2)方法
3.重写方法时,一定要注意排序规则,必须按照排序的主要规则和次要规则来写
重写compare(T t1,T t2)方法
//innerClass TreeSet<Student> treeSet=new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) {//Student o1 :将要存的数 Student o2 :已经存了的 int result = o1.getAge() - o2.getAge(); result=result==0?o1.getName().compareTo(o2.getName()):result; return result; } });
//lamada TreeSet<Student> treeSet=new TreeSet<>((a,b)->{ int result = a.getAge() - b.getAge(); result = result == 0 ? a.getName().compareTo(b.getName()) : result ; return result; }); treeSet.add(new Student("zhangsan",12)); treeSet.add(new Student("xiaoming",12)); treeSet.add(new Student("lisi",15)); treeSet.add(new Student("wanwu",13)); treeSet.add(new Student("wanwu",14)); for (Student student : treeSet) { System.out.println(student); }
原文:https://www.cnblogs.com/waacode/p/14738633.html