在使用Collections.sort进行排序时,如果被排序的对象没有实现Comparable接口或者需要自定义排序规则时,则需要我们指定一个比较器,方法的定义如下
public staticvoid sort(List list, Comparator super T> c) { list.sort(c); }
那怎样是升序,怎样是降序,又该怎样记住这个规则呢,我们来验证一下
首先我们定义User实体,包含name, age等字段
@Data
public class User {
private String name;
private Integer age;
private String phone;
private List friends;
@Override
public String toString() {
return "User{" +
"name='" + name + ''' +
", age=" + age +
", phone='" + phone + ''' +
", friends=" + StringUtils.join(friends,",") +
'}';
}
}
编写测试方法,对年龄进行排序
@Test
public void testSort() {
List list = new ArrayList<>();
for (int i=0; i<10; i++) {
User u = new User();
u.setName("二王" + i);
u.setAge(i);
list.add(u);
}
Collections.sort(list, (o1, o2) -> {
if (o1.getAge() < o2.getAge()) {
return -1;
}
if (o1.getAge() > o2.getAge()) {
return 1;
}
return 0;
});
System.out.println(StringUtils.join(list, "n"));
}
当o1年龄小于o2时返回-1,大于时返回1,此时打印出来的结果是按age字段升序进行排序
User{name='二王0', age=0, phone='null', friends=null}
User{name='二王1', age=1, phone='null', friends=null}
User{name='二王2', age=2, phone='null', friends=null}
User{name='二王3', age=3, phone='null', friends=null}
User{name='二王4', age=4, phone='null', friends=null}
User{name='二王5', age=5, phone='null', friends=null}
User{name='二王6', age=6, phone='null', friends=null}
User{name='二王7', age=7, phone='null', friends=null}
User{name='二王8', age=8, phone='null', friends=null}
User{name='二王9', age=9, phone='null', friends=null}
当o1年龄小于o2时返回1,大于时返回-1,此时打印出来的结果是按age字段降序进行排序
User{name='二王9', age=9, phone='null', friends=null}
User{name='二王8', age=8, phone='null', friends=null}
User{name='二王7', age=7, phone='null', friends=null}
User{name='二王6', age=6, phone='null', friends=null}
User{name='二王5', age=5, phone='null', friends=null}
User{name='二王4', age=4, phone='null', friends=null}
User{name='二王3', age=3, phone='null', friends=null}
User{name='二王2', age=2, phone='null', friends=null}
User{name='二王1', age=1, phone='null', friends=null}
User{name='二王0', age=0, phone='null', friends=null}
结论
通过前面的测试,我们可以这样来记住排序的规则:
比较器的参数1(o1)和参数2(o2),我们默认此时是o1排在前面,o2排在后面
当比较器返回1时表示o1和o2需要交换位置,即将o2排到前面,o1排到后面
当比较器返回-1时表示o1和o2不需要交换位置,即o1仍然排到前面,o2排到后面
比如下面判断,o1默认排在前面,o2排在后面,如果o1的年龄小于o2返回1,表示要交换位置,交换后就是年龄大的o2排在前面,年龄小的o1排在后面,即为按年龄倒序排序。反之亦然
Collections.sort(list, (o1, o2) -> {
if (o1.getAge() < o2.getAge()) {
return 1;
}
if (o1.getAge() > o2.getAge()) {
return -1;
}
return 0;
});



