如何将地图列表转换为地图
How to transform a list of maps to map
我有一个地图列表 (Map)
List<Map<Long, Long>> listMap = List.of(
Map.of(10L, 11L),
Map.of(20L, 21L),
Map.of(30L, 31L));
我想将其转换为 Map
Map<Long, Long> newMap = Map.of(
10L, 11L,
20L, 21L,
30L, 31L);
这是我的解决方案 - 增强了循环。
Map<Long, Long> newMap = new HashMap<>();
for (Map<Long, Long> map : listMap) {
Long key = (Long) map.keySet().toArray()[0];
newMap.put(key, map.get(key));
}
有没有更好的方法?我可以使用 Java 流进行此转换吗?
注意:密钥是唯一的 - 没有重复项。
很简单。获取底层映射的所有条目的流,并使用 Collectors.toMap
进行收集
Map<Long, Long> newMap = listMap.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
如果有重复键,你说不会,它会抛出
java.lang.IllegalStateException: Duplicate key <thekey>
您可以flatMap
将每个地图的列表条目展平并使用 Collectors.toMap
收集为地图
Map<Long, Long> newMap =
listMap.stream()
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
我有一个地图列表 (Map
List<Map<Long, Long>> listMap = List.of(
Map.of(10L, 11L),
Map.of(20L, 21L),
Map.of(30L, 31L));
我想将其转换为 Map
Map<Long, Long> newMap = Map.of(
10L, 11L,
20L, 21L,
30L, 31L);
这是我的解决方案 - 增强了循环。
Map<Long, Long> newMap = new HashMap<>();
for (Map<Long, Long> map : listMap) {
Long key = (Long) map.keySet().toArray()[0];
newMap.put(key, map.get(key));
}
有没有更好的方法?我可以使用 Java 流进行此转换吗?
注意:密钥是唯一的 - 没有重复项。
很简单。获取底层映射的所有条目的流,并使用 Collectors.toMap
Map<Long, Long> newMap = listMap.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
如果有重复键,你说不会,它会抛出
java.lang.IllegalStateException: Duplicate key <thekey>
您可以flatMap
将每个地图的列表条目展平并使用 Collectors.toMap
Map<Long, Long> newMap =
listMap.stream()
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));