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

相关推荐
游乐码14 分钟前
c#泛型约束
开发语言·c#
Dontla26 分钟前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen27 分钟前
python rest请求、requests
开发语言·python
铁东博客33 分钟前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui34 分钟前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳36 分钟前
Python从入门到精通day63
开发语言·python
lbb 小魔仙36 分钟前
Python_RAG知识库问答系统实战指南
开发语言·python
java1234_小锋36 分钟前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试
末央&1 小时前
【天机论坛】项目环境搭建和数据库设计
java·数据库
枫叶落雨2222 小时前
ShardingSphere 介绍
java