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

相关推荐
csbysj202015 小时前
PHP Mail - 发送邮件的最佳实践指南
开发语言
我命由我1234515 小时前
Android多进程开发 - AIDL 最简单的实现、传递数据大小限制
android·java·java-ee·kotlin·android studio·android jetpack·android-studio
jdbcaaa15 小时前
Go 语言 runtime 包的使用与注意事项
开发语言·后端·golang·runtime
ZHOUPUYU17 小时前
PHP 8.3网关优化:我用JIT将QPS提升300%的真实踩坑录
开发语言·php
寻寻觅觅☆21 小时前
东华OJ-基础题-106-大整数相加(C++)
开发语言·c++·算法
l1t1 天前
在wsl的python 3.14.3容器中使用databend包
开发语言·数据库·python·databend
青云计划1 天前
知光项目知文发布模块
java·后端·spring·mybatis
赶路人儿1 天前
Jsoniter(java版本)使用介绍
java·开发语言
ceclar1231 天前
C++使用format
开发语言·c++·算法
探路者继续奋斗1 天前
IDD意图驱动开发之意图规格说明书
java·规格说明书·开发规范·意图驱动开发·idd