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

相关推荐
i***39583 分钟前
Springboot中SLF4J详解
java·spring boot·后端
charlie11451419110 分钟前
勇闯前后端Week2:后端基础——HTTP与REST
开发语言·网络·笔记·网络协议·学习·http
z***948413 分钟前
springboot和springframework版本依赖关系
java·spring boot·后端
p***950022 分钟前
spring Profile
java·数据库·spring
艺杯羹23 分钟前
从Spring到SpringBoot3的演进:缺陷、优化与最新实践要求
java·spring boot·spring
一 乐28 分钟前
宠物管理宠物医院管理|基于Java+vue的宠物医院管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·宠物
一 乐29 分钟前
学习辅导系统|数学辅导小程序|基于java+小程序的数学辅导小程序设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·学习·小程序
励志成为糕手32 分钟前
基于SpringBoot的企业考勤管理系统设计与实现
java·spring boot·后端·web·企业应用
福尔摩斯张36 分钟前
二维数组详解:定义、初始化与实战
linux·开发语言·数据结构·c++·算法·排序算法
大佬,救命!!!42 分钟前
C++函数式策略模式代码练习
开发语言·c++·学习笔记·学习方法·策略模式·迭代加深·多文件编译