java中stream可以对数据集合进行排序,而且还可以指定分组排序,这里罗列出常用的情景。
假设数据集合中的元素是Person
,字段的属性如下所示
@Data
public static class Person {
private Date birthDay;
private String name;
private Integer age;
private String date;
public Person(Date birthDay, String name, Integer age) {
this.birthDay = birthDay;
this.name = name;
this.age = age;
this.date = new SimpleDateFormat("yyyy-MM-dd").format(this.birthDay);
}
}
初始化数据:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<Person> datas = new ArrayList<>();
datas.add(new Person(sdf.parse("2020-05-01 12:01:23"), "abc", 10));
datas.add(new Person(sdf.parse("2020-05-02 12:01:23"), "cde", 99));
datas.add(new Person(sdf.parse("2020-05-03 12:01:23"), "1234", 8));
datas.add(new Person(sdf.parse("2020-05-01 12:01:00"), "xxx", 19));
datas.add(new Person(sdf.parse("2020-05-02 02:01:23"), "111", 13));
场景: 分组排序
按照日期getDate来倒序分组,里面放着生日getBirthDay
也是倒序的数据
Map<String, List<Person>> sortedDatas = datas.stream()
.sorted(Comparator.comparing(Person::getBirthDay, Comparator.nullsLast(Comparator.reverseOrder())))
.collect(Collectors.groupingBy(Person::getDate, LinkedHashMap::new, Collectors.toList()));
这里先使用getBirthDay全局倒序,然后照着分组getDate分组,这里需要注意的是使用LinkedHashMap
不然系统会缺省使用HashMap
来构建
打印代码如下
// 打印数据
for (Map.Entry<String, List<Person>> elem : sortedDatas.entrySet()) {
System.out.println("key:" + elem.getKey());
for (Person p : elem.getValue()) {
System.out.println("\t"+p.toString());
}
}
打印内容
key:2020-05-03
TestGroupSort.Person(birthDay=Sun May 03 12:01:23 CST 2020, name=1234, age=8, date=2020-05-03)
key:2020-05-02
TestGroupSort.Person(birthDay=Sat May 02 12:01:23 CST 2020, name=cde, age=99, date=2020-05-02)
TestGroupSort.Person(birthDay=Sat May 02 02:01:23 CST 2020, name=111, age=13, date=2020-05-02)
key:2020-05-01
TestGroupSort.Person(birthDay=Fri May 01 12:01:23 CST 2020, name=abc, age=10, date=2020-05-01)
TestGroupSort.Person(birthDay=Fri May 01 12:01:00 CST 2020, name=xxx, age=19, date=2020-05-01)