- groupingBy()是Stream API中最強大的收集器Collector之一,提供與SQL的GROUP BY子句類似的功能。
- 需要指定一個屬性才能使用,通過該屬性執(zhí)行分組。我們通過提供功能接口的實現(xiàn)來實現(xiàn)這一點 - 通常通過傳遞lambda表達式。
一、默認升序排序
stationMap = peopleList.stream().collect(Collectors.groupingBy(People::getJgId));
二、descendingMap()降序排序
stationMap = peopleList.stream().collect(Collectors.groupingBy(People::getJgId,TreeMap::new,Collectors.toList())).descendingMap();
三、總結(jié)
TreeMap默認按照key升序排序,collectPlan.descendingMap()可以進行降序排序文章來源:http://www.zghlxwxcb.cn/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轉(zhuǎn)為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());
文章來源地址http://www.zghlxwxcb.cn/news/detail-531614.html
到了這里,關(guān)于Java8的stream之groupingBy()分組排序的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!