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

相关推荐
catchadmin2 分钟前
免费可商用 PHP 管理后台 CatchAdmin V5.3.1 发布 后台打包直降 5s 内
开发语言·php
小江的记录本6 分钟前
【Spring AI】Spring AI中RAG误触发与系统提示词泄露问题解决方案(完整版+代码方案)
java·人工智能·spring boot·后端·python·spring·面试
YY&DS12 分钟前
Qt Designer 自定义控件已提升后,如何修改提升类
开发语言·qt
勇往直前plus13 分钟前
Python 属性访问与操作全解析:内置函数、魔法方法与描述符深度指南
java·网络·python
Arenaschi19 分钟前
关于GPT的版特点
java·网络·人工智能·windows·python·gpt
人道领域19 分钟前
【LeetCode刷题日记】108.将有序数组转换为二叉搜索树
java·算法·leetcode
右耳朵猫AI21 分钟前
Rust技术周刊 2026年第19周
开发语言·后端·rust
橙淮26 分钟前
并发编程(五)
java
Leweslyh32 分钟前
基于 Confucius 架构的无人集群网络控制原语解析
开发语言·网络·php
过期动态34 分钟前
【LeetCode 热题 100】无重复字符的最长子串
java·数据结构·spring boot·算法·leetcode·职场和发展