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

相关推荐
v***5654 分钟前
常见的 Spring 项目目录结构
java·后端·spring
free-elcmacom7 分钟前
MATLAB物理仿真<1>电磁场有限元仿真
开发语言·matlab·电磁场仿真
Emilia486.9 分钟前
C++ 类与对象:解锁面向对象编程的核心密码(上)
开发语言·c++
超频化石鱼11 分钟前
使用Postman访问siliconflow大模型接口
java·postman·ai编程
f***453212 分钟前
SpringCloud篇(配置中心 - Nacos)
java·spring·spring cloud
b***666112 分钟前
Spring Framework 中文官方文档
java·后端·spring
成豆o((⊙﹏⊙))o.14 分钟前
C语言基础知识,仅供自己参考
c语言·开发语言
行走在电子领域的工匠16 分钟前
台达ST:自定义串行通讯传送与接收指令COMRS程序范例二
开发语言
7***477119 分钟前
【SQL】掌握SQL查询技巧:数据分组与排序
java·jvm·sql
Sally_xy21 分钟前
Python 虚拟环境
开发语言·chrome·python