java用stream将List<Map<String,String>>以其中一个元素为key转为Map<String,List<String>>
时间: 2023-07-09 21:37:56 浏览: 174
可以使用Java 8的Stream API将List<Map<String,String>>以其中一个元素为key转为Map<String,List<String>>,代码如下:
```java
List<Map<String,String>> list = new ArrayList<>();
Map<String,String> map1 = new HashMap<>();
map1.put("key1","value1");
map1.put("key2","value2");
map1.put("key3","value3");
list.add(map1);
Map<String,String> map2 = new HashMap<>();
map2.put("key1","value4");
map2.put("key2","value5");
map2.put("key3","value6");
list.add(map2);
String key = "key1";
Map<String,List<String>> result = list.stream()
.collect(Collectors.groupingBy(
m -> m.get(key),
Collectors.mapping(m -> m.get(key), Collectors.toList())));
System.out.println(result);
```
其中,key为要转为Map的元素的key,result为转换后的Map。运行以上代码会输出以下结果:
```
{value1=[value1], value4=[value4]}
```
其中,key为元素的值,value为对应元素的List。
阅读全文