将<String,List <String >>映射到Pair <String,String>

Viv*_*oel 4 java lambda java-8 java-stream

使用Java 8 Stream API,我该如何平铺MapPair列出左对值是映射键的位置?

示例:如果给定的地图是

1 => {1, 2, 3}
2 => {2, 4}
Run Code Online (Sandbox Code Playgroud)

然后所需的输出是五对流:

(1,1) , (1,2) , (1,3) , (2,2) , (2,4)
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

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