0

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.

djm.im
  • 3,295
  • 4
  • 30
  • 45

2 Answers2

4

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()));
Eklavya
  • 17,618
  • 4
  • 28
  • 57
3

Simple enough. Get a stream of all the entries of the underlying maps, and collect with Collectors.toMap

Map<Long, Long> newMap = listMap.stream()
    .flatMap(map -> map.entrySet().stream())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

If there is a duplicate key, which you said there will not be, it will throw

java.lang.IllegalStateException: Duplicate key <thekey>
Michael
  • 41,989
  • 11
  • 82
  • 128