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 分钟前
Envoy TCP 层面的 Metric 指标分析
开发语言·网络·网络协议·tcp/ip·php
逸Y 仙X10 分钟前
文章二十:Elasticsearch高亮搜索完全指南
java·大数据·运维·elasticsearch·搜索引擎·全文检索
清水白石00812 分钟前
生成器不是性能银弹:什么时候该用 `yield` 省内存,什么时候它会拖慢 Python 数据处理吞吐?
开发语言·python·原型模式
不甘先生14 分钟前
Go context 实战指南:从入门到生产级并发控制(架构师避坑手册)
开发语言·后端·golang
AI进化营-智能译站15 分钟前
ROS2 C++开发系列18-STL容器实战:deque缓存激光雷达数据|priority_queue调度任务
开发语言·c++·缓存·ai
Lyyaoo.22 分钟前
【JAVA Spring面经】Spring 事务失效情况
java·数据库·spring
初心未改HD30 分钟前
Go 泛型完全指南:从入门到实战
开发语言·golang
salipopl30 分钟前
Spring Boot 整合 Druid 并开启监控
java·spring boot·后端
西红柿炒番茄3134 分钟前
【Python】一个自动切换壁纸的python程序
开发语言·python
ShiJiuD66688899937 分钟前
JSP Cookie和Session
java·开发语言