Collectors.groupingBy():根据一个或多个属性对集合中的项目进行分组,demo如下,
//分组排序并加序号
Map<Integer, List<People>> stationMap = new HashMap<Integer, List<People>>();
// 使用stream流将list转为map,key为指定字段的值
stationMap = peopleList.stream().collect(Collectors.groupingBy(People::getJgId));
System.out.println(stationMap);
// 使用stream流将list转为map,key为指定字段的值,然后倒序排序
stationMap = peopleList.stream().collect(Collectors.groupingBy(People::getJgId, TreeMap::new, Collectors.toList())).descendingMap();
本次需求需要对得到的数据根据时间进行分组和排序,查询了一些,找到了需要的,记录一下,总之还是对java8的特性不熟悉导致;结果如下
//根据日期字段的 yyyy-MM 进行分组
Map<String, List<SomeEntity>> monthMap = someEntityList.stream().collect(Collectors.groupingBy(p -> cn.hutool.core.date.DateUtil.format(p.getOrderTime(), "yyyy-MM")));