Java8使用stream流
給List<Map<String,Object>>根據(jù)字段key分組
一、項(xiàng)目場(chǎng)景:
從已得到的List集合中,根據(jù)某一元素(這里指map的key)進(jìn)行分組,篩選出需要的數(shù)據(jù)。
如果是SQL的話則使用group by
直接實(shí)現(xiàn),代碼的方式則如下:
使用到stream流的Collectors.groupingBy()
方法。
二、代碼實(shí)現(xiàn)
1、首先將數(shù)據(jù)add封裝到List中,完成數(shù)據(jù)準(zhǔn)備。
//groupList用于庫(kù)-表分組的list,減少jdbc連接時(shí)間
List<Map<String,Object>> groupList = new ArrayList<>();
Map<String,Object> map1 = new HashMap<>();
map.put("name","張三");
map.put("age",20);
Map<String,Object> map2 = new HashMap<>();
map.put("name","李四");
map.put("age",20);
//excel每行的值存入集合中
groupList.add(map1);
groupList.add(map2);
2、然后按照name屬性進(jìn)行分組(單字段
),使用stream流分組
//分組判斷,stream流
Map<String, List<Map<String, Object>>> listMap =
groupList.stream().collect(
Collectors.groupingBy(item -> item.get("name").toString())
);
··按照name,age屬性進(jìn)行分組(多字段
),使用stream流分組
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-434494.html
//分組判斷,stream流
Map<String, List<Map<String, Object>>> listMap =
groupList.stream().collect(
Collectors.groupingBy(item -> item.get("name").toString()+"|"+item.get("age"))
);
3、遍歷結(jié)果,輸出查看
得到Map<String, List<Map<String, Object>>>,
key是你分組的字段,value分組下對(duì)應(yīng)的值。
也就是group by的效果。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-434494.html
for (String groupKey : listMap.keySet()) {
//分組key
System.out.println("分組Key: "+groupKey);
System.out.println("分組Key的value: "+listMap.get("groupKey"));
}
到了這里,關(guān)于Java8使用stream流給List<Map<String,Object>>分組(多字段key)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!