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

相关推荐
不败公爵2 分钟前
finsh_thread_entry这个线程是自动启动的
java·linux·服务器
Seven972 分钟前
Tomcat的事件监听机制:观察者模式
java
Ulyanov3 分钟前
《PySide6 GUI开发指南:QML核心与实践》 第五篇:Python与QML深度融合——数据绑定与交互
开发语言·python·qt·ui·交互·雷达电子战系统仿真
YaBingSec5 分钟前
玄机靶场-第三届-长城杯-初赛-SnakeBackdoor WP
java·运维·笔记·tomcat·ssh
IT利刃出鞘14 分钟前
Spring工具类--AnnotationUtils的使用
java·spring
wengqidaifeng1 小时前
C++从菜鸟到强手:1.基础入门
开发语言·c++
我喜欢山,也喜欢海1 小时前
Java和go在并发上的表现为什么不一样
java·python·golang
hhb_6181 小时前
PHP 8.x 核心特性与工程化开发实践指南
开发语言·php
geovindu2 小时前
go: Flyweight Pattern
开发语言·设计模式·golang·享元模式
Wenzar_2 小时前
**零信任架构下的微服务权限控制:用Go实现基于JWT的动态访问策略**在现代云原生环境中,
java·python·微服务·云原生·架构