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

相关推荐
初夏睡觉4 分钟前
c++1.3(变量与常量,简单数学运算详解),草稿公放
开发语言·c++
升职佳兴11 分钟前
C盘爆满自救:3步无损迁移应用数据到E盘(含回滚)
c语言·开发语言
ID_1800790547315 分钟前
除了 Python,还有哪些语言可以解析 JSON 数据?
开发语言·python·json
周末也要写八哥1 小时前
多进程和多线程的特点和区别
java·开发语言·jvm
惜茶2 小时前
vue+SpringBoot(前后端交互)
java·vue.js·spring boot
宁瑶琴2 小时前
COBOL语言的云计算
开发语言·后端·golang
杰克尼2 小时前
springCloud_day07(MQ高级)
java·spring·spring cloud
小陈工2 小时前
2026年4月2日技术资讯洞察:数据库融合革命、端侧AI突破与脑机接口产业化
开发语言·前端·数据库·人工智能·python·安全
Zarek枫煜3 小时前
C3 编程语言 - 现代 C 的进化之选
c语言·开发语言·青少年编程·rust·游戏引擎
阿kun要赚马内3 小时前
Python中元组和列表差异:底层结构分析
开发语言·python