java将List<Map<String,String>>以其中一个元素为key转为Map<String,List<String>>
时间: 2023-07-09 12:37:56 浏览: 92
可以通过以下代码将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 = new HashMap<>();
for(Map<String,String> map : list){
String value = map.get(key);
if(result.containsKey(value)){
result.get(value).add(map.get(key));
}else{
List<String> valueList = new ArrayList<>();
valueList.add(map.get(key));
result.put(value, valueList);
}
}
System.out.println(result);
```
其中,key为要转为Map的元素的key,result为转换后的Map。运行以上代码会输出以下结果:
```
{value1=[value1], value4=[value4]}
```
其中,key为元素的值,value为对应元素的List。
阅读全文