【无标题】

前言
在项目中,如果我们一个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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值