Issue
I have a list of maps (Map<Long, Long>)
List<Map<Long, Long>> listMap = List.of(
Map.of(10L, 11L),
Map.of(20L, 21L),
Map.of(30L, 31L));
And I want to transform it into a Map<Long, Long>
Map<Long, Long> newMap = Map.of(
10L, 11L,
20L, 21L,
30L, 31L);
This is my solution - with enhancement for loop.
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));
}
Is there a better approach? Can I use Java streams for this transformation?
Note: Keys are unique - no duplicates.
Solution
You can flatMap
to flatten every map's entry of list and collect as a map using Collectors.toMap
Map<Long, Long> newMap =
listMap.stream()
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
Answered By - Eklavya
Answer Checked By - Mary Flores (JavaFixing Volunteer)