相关推荐recommended
Java8使用stream流给List<Map<String,Object>>分组(多字段key)
作者:mmseoamin日期:2023-12-25
Java8使用stream流给List>根据字段key分组

一、项目场景:

从已得到的List集合中,根据某一元素(这里指map的key)进行分组,筛选出需要的数据

如果是SQL的话则使用group by直接实现,代码的方式则如下:

使用到stream流的Collectors.groupingBy()方法。

二、代码实现

1、首先将数据add封装到List中,完成数据准备。

//groupList用于库-表分组的list,减少jdbc连接时间
List> groupList = new ArrayList<>();
Map map1 = new HashMap<>();
map.put("name","张三");
map.put("age",20);
Map map2 = new HashMap<>();
map.put("name","李四");
map.put("age",20);
//excel每行的值存入集合中
groupList.add(map1);
groupList.add(map2);

2、然后按照name属性进行分组(单字段),使用stream流分组

//分组判断,stream流
Map>> listMap =
		groupList.stream().collect(
			Collectors.groupingBy(item -> item.get("name").toString())
		);

··按照name,age属性进行分组(多字段),使用stream流分组

//分组判断,stream流
Map>> listMap =
		groupList.stream().collect(
			Collectors.groupingBy(item -> item.get("name").toString()+"|"+item.get("age"))
		);

3、遍历结果,输出查看

得到Map>>,

key是你分组的字段,value分组下对应的值。

也就是group by的效果。

for (String groupKey : listMap.keySet()) {
	//分组key
	System.out.println("分组Key: "+groupKey);
	System.out.println("分组Key的value: "+listMap.get("groupKey"));
}