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

相关推荐
quantdash_cc5 分钟前
Python 股票 K 线数据质量校验:字段、缺失值、重复行和价格异常
开发语言·python·数据分析·量化交易·股票数据·quantdash
Zenova EdgeOS6 分钟前
工业网关重试机制:从固定间隔到指数退避的工程实战
开发语言·网络·php
嘻哈baby23 分钟前
Go 函数中的参数为什么不支持默认值?
java·开发语言·jvm
慧都小项27 分钟前
MyEclipse 2026:当 Agent、MCP 与 Java 26 进入 Eclipse 工作流
java·eclipse·springboot·copilot·myeclipse
一晌小贪欢29 分钟前
python-第29天:Python面向对象之多态与抽象类
开发语言·python·数据可视化·面向对象·python办公·python多态
Chester_199936 分钟前
CSP202312C.树上搜索
开发语言·数据结构·c++·蓝桥杯·stl
Figo_Cheung1 小时前
Figo共振网络宇宙演化论(RNC) :从原初对称破缺到全息大和谐的演化路径研究
开发语言·php·量子计算
重生之我来学Python1 小时前
Git-SVN 混合开发,从入门到精通!
开发语言·git·svn·github
CoderYanger1 小时前
前端基础——JavaScript(基础语法)(下篇)
java·开发语言·前端·javascript·程序人生·面试·职场和发展
京师20万禁军教头1 小时前
39面向对象(高级)-设计模式
java·开发语言·设计模式