- groupingBy()是Stream API中最强大的收集器Collector之一,提供与SQL的GROUP BY子句类似的功能。
- 需要指定一个属性才能使用,通过该属性执行分组。我们通过提供功能接口的实现来实现这一点 - 通常通过传递lambda表达式。
一、默认升序排序
stationMap = peopleList.stream().collect(Collectors.groupingBy(People::getJgId));
二、descendingMap()降序排序
stationMap = peopleList.stream().collect(Collectors.groupingBy(People::getJgId,TreeMap::new,Collectors.toList())).descendingMap();
三、总结
TreeMap默认按照key升序排序,collectPlan.descendingMap()可以进行降序排序文章来源:https://www.toymoban.com/news/detail-531614.html
List<People> peopleList = Lists.newArrayList();
peopleList.add(new People(1, "小王", 5));
peopleList.add(new People(1, "小李", 4));
peopleList.add(new People(2, "小张", 3));
peopleList.add(new People(2, "小皇", 2));
peopleList.add(new People(2, "小刘", 1));
//分组排序并加序号
Map<Integer, List<People>> stationMap = new HashMap<Integer, List<People>>();
// 使用stream流将list转为map,key为指定字段的值
stationMap = peopleList.stream().collect(Collectors.groupingBy(People::getJgId));
log.info(stationMap.toString());
stationMap = peopleList.stream().collect(Collectors.groupingBy(People::getJgId,TreeMap::new,Collectors.toList())).descendingMap();
log.info(stationMap.toString());
文章来源地址https://www.toymoban.com/news/detail-531614.html
到了这里,关于Java8的stream之groupingBy()分组排序的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!