Map> to Pair

2019-05-11 00:52发布

问题:

Using Java 8 Stream API how can I flat a Map to Pair list where left pair value is the map key?

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)

回答1:

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