stream流对集合排序,多字段排序(升序和降序)(空值排到最后)

1、实体类
stream流对集合排序,多字段排序(升序和降序)(空值排到最后)_第1张图片
2、集合数据

student student4 = new student();
            //student4.setId("4");
            student4.setName("4");
            student student5 = new student();
            student5.setId("5");
            student5.setName("5");
            student student6 = new student();
            student6.setId("4");
            student6.setName("4");
            List<student> list2 = new ArrayList<>();
            list2.add(student4);
            list2.add(student5);
            list2.add(student6);
            System.out.println(list2);

3、集合排序,空值最后(空值建议加上,以防id为空执行报错)

list2 = list2.stream().sorted(Comparator.comparing(student::getId,Comparator.nullsFirst(String::compareTo)).reversed())
                    .collect(Collectors.toList());//倒叙
                    
 list2 = list2.stream().sorted(Comparator.comparing(student::getId,Comparator.nullsLast(String::compareTo)))
                    .collect(Collectors.toList());//升序   
                    
list2 = list2.stream().sorted(Comparator.comparing(student::getId,Comparator.nullsLast(String::compareTo)).reversed().thenComparing(student::getName))
                    .collect(Collectors.toList());//id降序,名字升序               

你可能感兴趣的:(笔记,java,排序算法,开发语言)