Java 8 合并 Map 集合的 Value 为一个 Set 集合
要将多个 Map 的 Value 合并为一个 Set 集合,可以使用 Java 8 的 Stream API 来实现。以下是一个示例代码:
import java.util.*;
public class MergeMaps {
public static void main(String[] args) {
Map<String, Set<Integer>> map1 = new HashMap<>();
map1.put('A', new HashSet<>(Arrays.asList(1, 2, 3)));
map1.put('B', new HashSet<>(Arrays.asList(4, 5)));
Map<String, Set<Integer>> map2 = new HashMap<>();
map2.put('C', new HashSet<>(Arrays.asList(6, 7, 8)));
map2.put('D', new HashSet<>(Arrays.asList(9, 10, 11)));
Set<Integer> mergedSet = Stream.of(map1, map2)
.flatMap(map -> map.values().stream())
.flatMap(Set::stream)
.collect(Collectors.toSet());
System.out.println(mergedSet); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
}
}
在上面的示例中,我们创建了两个 Map 对象,每个 Map 对象的 Value 都是一个 Set 集合。然后,我们使用 Stream 的 flatMap() 方法来将多个 Map 的 Value 流合并为一个流。最后,我们通过 collect() 方法将流转换为 Set 集合。
请注意,Stream.of() 方法接受一个可变参数,所以你可以传入任意数量的 Map 对象。
原文地址: https://www.cveoy.top/t/topic/quyC 著作权归作者所有。请勿转载和采集!