java list<map<string, string>>如何转为map<string, list>,并给出示例
时间: 2023-03-15 08:10:46 浏览: 177
Java三种方法将List转换为Map的实例
可以通过以下方法进行转换: 1. 首先,使用 Java 的 Stream API 将 List<Map<String, String>> 转换为 Map<String, List<String>>:Map<String, List<String>> result = list.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));2. 然后可以使用 Map.Entry 对象(Entry 是 Map 中键值对的一个抽象表示)将 Map<String, List<String>> 转换为 Map<String, String>:Map<String, String> result2 = result.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(),
e -> e.getValue().stream()
.collect(Collectors.joining(","))));示例:
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map1 = new HashMap<>();
map1.put("name", "zhangsan");
map1.put("age", "20");
Map<String, String> map2 = new HashMap<>();
map2.put("name", "lisi");
map2.put("age", "21");
list.add(map1);
list.add(map2);Map<String, List<String>> result = list.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));Map<String, String> result2 = result.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey(),
e -> e.getValue().stream()
.collect(Collectors.joining(","))));// result2 = {name=zhangsan,lisi, age=20,21}
阅读全文