Search code examples
collectionsjava-streamflatmap

Swapping and flattening a Java Map<Integer, List<Integer>> using Stream API


Having this Map<Integer, List>:

Map<Integer, List<Integer>> forwardMap = Map.of(
        100, List.of(6),
        300, List.of(49, 52),
        500, List.of(293)
);

I would like to 'flatten' the value Lists and swap the key and value in the Map, ending up with this:

Map<Integer, Integer> reverseMap = Map.of(
         6, 100,
        49, 300
        52, 300,
       293, 500
);

My cannot-compile attempt, where I attempt to stream the Set<Map.Entry> and then the nested List:

Map<Integer, Integer> reverseMap = forwardMap.entrySet().stream().map(
        entry -> entry.getValue().stream().collect(Collectors.toMap(Integer::getInteger, entry.getKey()));
);

Perhaps I need to avoid using stream() twice - possibly by using flatMap() somewhere and somehow. I have also tried first swapping swapping the key and value - but still end up not having a reference to the 'outer' key and the 'inner' nested Integers in the Lists, at the same time.

What am I missing or downright misunderstanding?


Solution

  • As part of your goal is to flatten the values, you're correct you'll probably need a flatMap operation somewhere. For example:

    Map<Integer, Integer> reverseMap =
        forwardMap.entrySet().stream()
            .flatMap(
                entry -> entry.getValue().stream().map(value -> Map.entry(value, entry.getKey())))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));