Using the Java 8 Stream API how can I flatten a Map<String,List<String>>
to Pair<String,String>
list where the left pair value is the map key and the right is the key in the list?
If given map was:
1 => {1, 2, 3}
2 => {2, 4}
Then desired output is the stream of five pairs:
(1,1) , (1,2) , (1,3) , (2,2) , (2,4)
List<Pair<String, String>> result =
map.entrySet()
.stream()
.flatMap(
entry -> entry.getValue()
.stream()
.map(string -> new Pair<>(entry.getKey(), string)))
.collect(Collectors.toList());