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

相关推荐
qq_334903154 分钟前
高性能网络协议栈
开发语言·c++·算法
阿贵---7 分钟前
模板编译期循环展开
开发语言·c++·算法
2601_954023667 分钟前
Beyond the Hype: Deconstructing the 2025 High-Performance Stack for Agencies
java·开发语言·算法·seo·wordpress·gpl
l1t12 分钟前
DeepSeek 辅助编写python程序求解欧拉计划932题:2025数
开发语言·python·欧拉计划
2401_8331977315 分钟前
嵌入式C++电源管理
开发语言·c++·算法
ms_27_data_develop18 分钟前
Java——集合
java·开发语言
灰色小旋风19 分钟前
力扣22 括号生成(C++)
开发语言·数据结构·c++·算法·leetcode
2501_9249526920 分钟前
模板编译期哈希计算
开发语言·c++·算法
xiaoye-duck23 分钟前
C++ STL map 系列深度解析:从底层原理、核心接口到实战场景
开发语言·c++·stl
编码忘我23 分钟前
java策略模式实战之优惠券
java·后端