Search code examples
javalambdajava-8java-stream

Convert Map<String,List<String>> to List<Pair<String,String>> using the Stream API


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?

Example

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)

Solution

  • List<Pair<String, String>> result =
        map.entrySet()
           .stream()
           .flatMap(
               entry -> entry.getValue()
                             .stream()
                             .map(string -> new Pair<>(entry.getKey(), string)))
           .collect(Collectors.toList());