Java之List.steam().sorted(Comparator.comparing())排序异常解决方案

使用steam().sorted(Comparator.comparing())对List<T>集合里的String类型字段进行倒序排序,发现倒序失效。记录解决方案。

异常代码如下:

java 复制代码
 customerVOList = customerVOList.stream()
                .sorted(Comparator.comparing(CustomerVOVO::getCustomerRate).reversed())
                .collect(Collectors.toList());

getCustomerRate 是String类型的,存的是double类型的值,要根据这个字段倒序返回,发现这种方法排序是乱的。

解决方案一

java 复制代码
        // 把String类型字段转换成Double类型进行自然升序排序
customerVOList = customerVOList.stream()
                                .sorted(Comparator.comparingDouble(v -> Double.valueOf(v.getCustomerRate())))
                                .collect(Collectors.toList());
        // 先自然排序然后再倒序
        Collections.reverse(customerLoanMapVOList);

这种方案需要先把String类型转换成Double类型自然升序排序后再使用Collections对集合进行倒序,reversed()用不了,用了就报错 "Cannot resolve method 'getCustomerRate' in 'Object'"。

解决方案二

java 复制代码
        customerVOList = customerVOList.stream()
                                .sorted((v1,v2) -> Double.valueOf(v2.getCustomerRate()).compareTo(Double.valueOf(v1.getCustomerRate())))
                                .collect(Collectors.toList());

直接不要Comparator,一段代码搞定。

延伸

使用steam().sorted(Comparator.comparing())对自定义对象集合中的字段进行排序,避免直接对String类型字段进行自定义规则排序,可能会出现未知问题。

相关推荐
用户0304805912632 分钟前
Spring Validation教程
java
Hello.Reader4 分钟前
DTO / VO / BO / Entity 分层到底怎么用?
java·分层
云梦谭5 分钟前
AI 生成的FreeSWITCH 呼出流程深度分析freeswitch-1.10.12.-release
java·前端·php
红石程序员10 分钟前
Python环境管理
开发语言·python
随机昵称_12345610 分钟前
RSA私钥解密乱码问题
java·非对称加密
Chennnng12 分钟前
关于python版本,显卡版本,torch版本之间的问题
开发语言·python
龙亘川12 分钟前
【课程2.4】开发环境搭建:K8s集群部署、芋道框架集成、ThingsBoard对接
java·容器·kubernetes·智慧城市·智慧城市一网统管 ai 平台
rit843249916 分钟前
基于MATLAB的多变量动态矩阵控制(DMC)仿真实现
开发语言·matlab·矩阵
pyniu24 分钟前
项目实站day7--功能之营业额统计,用户数量统计
java·开发语言·spring boot·spring
一周困⁸天.34 分钟前
K8S-NetworkPolicy
java·开发语言