如何使用Java 8 Stream API将Map扁平化为左对值为Map键的Pair列表?
示例: 如果给定的Map是
1 => {1, 2, 3}
2 => {2, 4}
那么期望的输出是五对流:
(1,1) , (1,2) , (1,3) , (2,2) , (2,4)
如何使用Java 8 Stream API将Map扁平化为左对值为Map键的Pair列表?
示例: 如果给定的Map是
1 => {1, 2, 3}
2 => {2, 4}
(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());