Invert Map with list value Map<Key, List<Value>> to Map <Value, Key> in Java 8
You can use
Map<Integer, String> mapNumberToType = mapOfIntList.entrySet().stream()
.collect(HashMap::new, (m,e)->e.getValue().forEach(v->m.put(v,e.getKey())), Map::putAll);
You may recognize the similarity to the forEach
based code of this answer within the second function passed to collect
(the accumulator) function. For a sequential execution, they do basically the same, but this Stream solution supports parallel processing. That’s why it needs the other two functions, to support creating local containers and to merge them.
See also the Mutable reduction section of the documentation.
Or use two nested forEach
mapOfIntList.forEach((key, value) ->
value.forEach(v -> {
mapNumberToType.put(v, key);
})
);
as @nullpointer commented in one-liner
mapOfIntList.forEach((key, value) -> value.forEach(v -> mapNumberToType.put(v, key)));
I have found a solution :
Map<Integer, String> mapNumberToType = mapOfIntList
.entrySet()
.stream()
.flatMap(
entry -> entry.getValue().stream()
.map(number -> Pair.of(number, entry.getKey()))
.collect(Collectors.toList()).stream())
.collect(
Collectors.toMap(Pair::getLeft,
Pair::getRight, (a, b) -> {
return a;
}));
System.out.println("Number/Type correspondance : " + mapNumberToType);
hope this helps anyone having the same problem !