stream流如何对集合排序(多字段排序(升序和降序)---(空值放最后))的效果呢?
下文笔者讲述stream对集合排序的方法分享,如下所示
stream对集合排序的实现思路
借助Comparator.comparing方法即可对集合排序例:Stream流对集合排序的示例
//1.实体类
public class student{
private String id;
private String name;
}
//2.集合数据
student student4 = new student();
//student4.setId("8");
student4.setName("maomao");
student student5 = new student();
student5.setId("9");
student5.setName("狗狗");
student student6 = new student();
student6.setId("10");
student6.setName("你最牛");
list<student> list2 = new ArrayList<>();
list2.add(student4);
list2.add(student5);
list2.add(student6);
System.out.println(list2);
//3.集合排序,空值最后
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降序,名字升序
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


