前言
在项目中,如果我们一个list是从数据库查出来,那么数据库就可以进行排序;但是有些list是进行各种拼接计算出来的,或者说单独计算的结果拼接起来的,那么我们就可以使用JAVA中针对List的Comparator.comparing进行排序,从而达到稳定性排序。
实现方法
1.首先你需要list.parallelStream().sorted 进行流处理,使用parallelStream可以充分调度多核CPU。
2.使用Comparator.comparing进行排序,reversed()进行倒序排列,thenComparing进行下一个排序。
3.Comparator.comparing()里面的内容,也是就是Object::getter,例如KeywordCounterDTO::getKeyword
4.最后格式化为需要的格式 List 是.collect(Collectors.toList()) , Map 是 .collect(Collectors.toMap(KeywordCounterDTO::getKey, KeywordCounterDTO::getValue))
//powered by zhengkai.blog.csdn.net
list = list.parallelStream().sorted(
Comparator.comparing(KeywordCounterDTO::getAllCounter).reversed().thenComparing(KeywordCounterDTO::getKeyword)
).collect(Collectors.toList());
使用 Comparator.reversed 进行排序
这是返回相反的排序规则,
/**
* 相反的排序规则
*/
Collections.sort(employees, Comparator.comparing(Employee::getName).reversed());
employees.forEach(System.out::println);
使用 Comparator.nullsFirst进行排序
当集合中存在null元素时,可以使用针对null友好的比较器,null元素排在集合的最前面
employees.add(null); //插入一个null元素
Collections.sort(employees, Comparator.nullsFirst(Comparator.comparing(Employee::getName)));
employees.forEach(System.out::println);
Collections.sort(employees, Comparator.nullsLast(Comparator.comparing(Employee::getName)));
employees.forEach(System.out::println);
使用 Comparator.thenComparing 排序
首先使用 name 排序,紧接着在使用ege 排序,
Collections.sort(employees, Comparator.comparing(Employee::getAge).thenComparing(Employee::getName));
employees.forEach(System.out::println);