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类型字段进行自定义规则排序,可能会出现未知问题。

相关推荐
TAN-90°-2 分钟前
Java 6——成员变量初始值 object equals和== toString instanceof 参数传递问题
java·开发语言
中新传媒4 分钟前
德宸堂心理双师同诊
java·前端·数据库
想唱rap11 分钟前
NAT、内网穿透、代理服务
java·linux·网络·网络协议·udp·智能路由器
故事和你9111 分钟前
洛谷-【图论2-1】树6
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
被AI抢饭碗的人12 分钟前
C++过渡Python
开发语言·python
不知名的老吴13 分钟前
在C++中不用宏怎么打日志的使用建议
开发语言·c++·算法
环流_18 分钟前
nacos环境隔离
java·服务器·前端
芋只因19 分钟前
天机学堂学习笔记
java·笔记·学习
jieyucx20 分钟前
Go 语言进阶:结构体指针、new 关键字与匿名结构体/成员详解
开发语言·后端·golang·结构体
摇滚侠25 分钟前
Spring 面试题 真正的 offer 偏方 Java 基础 Java 高级
java·后端·spring