Java中 List 集合,通过 Stream 流进行排序总结

一、数据准备

cpp 复制代码
public class OrderTest {
    private String channelCode;
    private BigDecimal rate;
    // 省略 getter、setter、toString()、constructor
}
cpp 复制代码
		List<OrderTest> orderTestList = new ArrayList<>();
        OrderTest z09 = new OrderTest("Z09", new BigDecimal("7.6677"));
        OrderTest B2C = new OrderTest("B2C", new BigDecimal("5.6666"));
        OrderTest Z04 = new OrderTest("Z04", new BigDecimal("4.3137"));
        OrderTest ALL = new OrderTest("ALL", new BigDecimal("4.3137"));
        OrderTest ALL1 = new OrderTest("ALL", new BigDecimal("4.5137"));
        // 演示多字段排序使用
        OrderTest z091 = new OrderTest("Z09", new BigDecimal("7.6671"));
        // 演示给 null 值排序用
        OrderTest z092 = new OrderTest("Z09", null);
        OrderTest B2C1 = new OrderTest("B2C", new BigDecimal("5.6666"));
        OrderTest Z041 = new OrderTest("Z04", null);
        orderTestList.add(z09);
        orderTestList.add(z091);
        orderTestList.add(B2C);
        orderTestList.add(Z04);
        orderTestList.add(ALL);
        orderTestList.add(ALL1);

二、单字段排序

2.1、升序

cpp 复制代码
 list.stram().sorted(Comparator.Comparing(YourClass::Class's Field)
cpp 复制代码
System.out.println("----------------------------------------------");
        System.out.println("只按照 channelCode 升序排序:");
        List<OrderTest> channelAsc =
                orderTestList.stream()
                        .sorted(Comparator.comparing(OrderTest::getChannelCode))
                        .collect(Collectors.toList());
        channelAsc.forEach(System.out::println);

结果:

2.2、降序

cpp 复制代码
 list.stram().sorted(Comparator.Comparing(YourClass::Class's Field, Comparator.reverseOrder())
cpp 复制代码
System.out.println("----------------------------------------------");
        System.out.println("只按照 channelCode 降序排序:");
        List<OrderTest> channelDesc =
                orderTestList.stream()
                        .sorted(Comparator.comparing(OrderTest::getChannelCode, Comparator.reverseOrder()))
                        .collect(Collectors.toList());
        channelDesc.forEach(System.out::println);

结果:

二、多字段排序

cpp 复制代码
利用的是 thenComparing():
升序 thenComparing(YourClass::Class's Field),
降序 thenComparing(YourClass::Class's Field, Comparator.reverseOrder())。

注意: 使用 thenComparing(YourClass::Class's Field).reversed() 的时候要注意排序要求,
如果先按照 A 字段升序 B 字段升序的话,使用 reversed() 之后的结果是对 A 降序 B 降序。
cpp 复制代码
System.out.println("----------------------------------------------");
        System.out.println("先按照 channelCode 升序,再按照 rate 升序排序:");
        List<OrderTest> channelCodeAscRateAscList =
                orderTestList.stream()
                        .sorted(Comparator.comparing(OrderTest::getChannelCode)
                                .thenComparing(OrderTest::getRate))
                        .collect(Collectors.toList());
        channelCodeAscRateAscList.forEach(System.out::println);

结果

先按照 channelCode 将序,再按照 rate 升序将序,使用 reversed():

cpp 复制代码
System.out.println("----------------------------------------------");
        System.out.println("先按照 channelCode 将序,再按照 rate 将序排序,使用 reversed():");
        List<OrderTest> channelCodeAscRateAscWithReversedList =
                orderTestList.stream()
                        .sorted(Comparator.comparing(OrderTest::getChannelCode)
                                .thenComparing(OrderTest::getRate).reversed())
                        .collect(Collectors.toList());
        channelCodeAscRateAscWithReversedList.forEach(System.out::println);

结果

三、对 null 值处理

cpp 复制代码
 Comparator.nullsFirst(Comparator.reverseOrder())  -- null排在前面,reverseOrder是倒序,升序用naturalOrder
 Comparator.nullsLast(Comparator.reverseOrder())   -- null排在后面,reverseOrder是倒序,升序用naturalOrder
cpp 复制代码
orderTestList.add(new OrderTest(("Z09")));
        orderTestList.add(new OrderTest(("B2C")));
        orderTestList.add(new OrderTest(("Z04")));
        System.out.println("----------------------------------------------");
        System.out.println("先按照 channelCode 升序,再按照 rate 降序并且 null 值放前面排序:");
        List<OrderTest> channelCodeAscRateDescNullFirstList = orderTestList.stream()
                .sorted(Comparator.comparing(OrderTest::getChannelCode)
                        .thenComparing(OrderTest::getRate, Comparator.nullsFirst(Comparator.reverseOrder())))
                .collect(Collectors.toList());
        channelCodeAscRateDescNullFirstList.forEach(System.out::println);

结果

四、对排序字段个数不固定的情况,如何排序

需求:排序字段个数不确定,如何实现动态排序?

伪代码示例:

cpp 复制代码
		Comparator<SurgUnArrangeResponse> comparing = null;
        for (int i = 0; i < dictItemList.size(); i++) {
            String cd = dictItemList.get(i).getCd();
            if (i == 0) {
                // 首次排序
                comparing = getComparingByDictCd(cd, null);
            } else {
            	// 第二次排序及以上
                comparing = getComparingByDictCd(cd, comparing);
            }
        }
        // comparing 比较器,保存了排序的规则,responseList 是被排序的集合
		responseList = responseList.stream().sorted(comparing)
						.collect(Collectors.toList());
		
		// getComparingByDictCd 方法
		private Comparator<SurgUnArrangeResponse> getComparingByDictCd(String dictCd, 
Comparator<SurgUnArrangeResponse> result = null;
        switch (dictCd) {
            case "age":
                result = comparing == null ? Comparator.comparing(SurgUnArrangeResponse::getAge, Comparator.nullsLast(Comparator.reverseOrder())) :
                        comparing.thenComparing(SurgUnArrangeResponse::getAge, Comparator.nullsLast(Comparator.reverseOrder()));
                break;
                ....
        	}
        	return result;
		}
相关推荐
waving-black8 分钟前
windows系统下安装测试kafka
windows·分布式·kafka
4Forsee19 分钟前
【Android】浅析 Android 的 IPC 跨进程通信机制
android·java
来旺33 分钟前
互联网大厂Java面试全解析及三轮问答专项
java·数据库·spring boot·安全·缓存·微服务·面试
Json____33 分钟前
使用node Express 框架框架开发一个前后端分离的二手交易平台项目。
java·前端·express
since �33 分钟前
前端转Java,从0到1学习教程
java·前端·学习
詩句☾⋆᭄南笙34 分钟前
Mybatis一对一、一对多
java·mybatis·resulttype·resultmap·一对多·一对一
Andya_net1 小时前
Java | 基于redis实现分布式批量设置各个数据中心的服务器配置方案设计和代码实践
java·服务器·分布式
lang201509281 小时前
Spring Boot 外部化配置最佳实践指南
java·spring boot
沐浴露z1 小时前
【JVM】详解 垃圾回收
java·jvm·算法
重生之我要当java大帝1 小时前
java微服务-尚医通-管理平台前端搭建-医院设置管理-4
java·开发语言·前端