場景:比如說有一個List<Student> 里面有許多學生 我們想讓這些學生按照年齡的大小排序
我們可以用java自帶的 java.util.Collections 工具類來實現
Collections.sort(rootList, studentComparator); public Comparator<Student> studentComparator = new Comparator<Student>() { public int compare(Student o1, Student o2) { return o1.getAge() - o2.getAge(); //從小到大 } };
解釋一下:sort方法 第一個是需要排序的list 第二個是排序的規則 規則是自己自定義的
多個字段排序,比如先排年齡,年齡相同再排姓名
Collections.sort(rootList, studentComparator); public Comparator<Student> studentComparator = new Comparator<Student>() { public int compare(Student o1, Student o2) { int age=o1.getAge() - o2.getAge(); if(age==0){ return o1.getName() - o2.getName(); }else{ return age; } } };