我如何接受集合的并集?

How do I take the union of sets?

是否有任何最佳方法来获得 n 集的所有并集?

这是我做过的,但是对于大量的集合来说很慢:

public static void main(String[] args) {
    List<List<Set<Integer>>> unionSet = new ArrayList<>();
    List<List<Integer>> sets = ...
    double avail = 0;
    for (int i = 1; i <= sets.size(); i++) {
        List<Set<Integer>> us = new ArrayList<>();
        union(sets, us, new HashSet<>(), i, 0);
        unionSet.add(us);
    }
}
public static void union(
        List<List<Integer>> sets, List<Set<Integer>> unionSet,
        Set<Integer> set, int size, int index) {
    for (int i = index; i < sets.size(); i++) {
        Set temp = new HashSet(set);
        temp.addAll(sets.get(i));

        if (size != 1)
            union(sets, unionSet, temp, size - 1, i + 1);
        else
            unionSet.add(temp);
    }
}

The intersection of all combinations of n sets

您可以使用Stream#flatMap方法如下:

  1. 如果你有一个 list of sets,你可以 flatten 其元素(即 sets)合并为一个 set 唯一值:

    List<Set<Integer>> setList =
            List.of(Set.of(1, 2, 3), Set.of(2, 3, 7));
    
    Set<Integer> set = setList.stream()
            .flatMap(Set::stream)
            .collect(Collectors.toSet());
    
    System.out.println(set); // [1, 2, 3, 7]
    
  2. 如果你有更深层级的嵌套,那么你必须执行更深的扁平化:

    List<List<Set<Integer>>> lists = List.of(
            List.of(Set.of(1, 2, 3), Set.of(2, 3, 4)),
            List.of(Set.of(3, 4, 5), Set.of(5, 1, 2)));
    
    Set<Integer> set = lists
            // Stream<List<Set<Integer>>>
            .stream()
            // Stream<Set<Integer>>
            .flatMap(List::stream)
            // Stream<Integer>
            .flatMap(Set::stream)
            .collect(Collectors.toSet());
    
    System.out.println(set); // [1, 2, 3, 4, 5]
    
  3. 如果您有 多个集合 ,嵌套级别 未知 ,您可以创建一个 通用递归展平 方法:

    public static void main(String[] args) {
        List<Set<Integer>> setList =
                List.of(Set.of(1, 2, 3), Set.of(2, 3, 7));
    
        List<List<Set<Integer>>> lists = List.of(
                List.of(Set.of(1, 2, 3), Set.of(2, 3, 4)),
                List.of(Set.of(3, 4, 5), Set.of(5, 1, 2)));
    
        Set<Integer> set = (Set<Integer>) toSet(setList, lists);
        System.out.println(set); // [1, 2, 3, 4, 5, 7]
    }
    
    public static Set<?> toSet(Collection<?>... collections) {
        return Arrays.stream(collections)
                .flatMap(col -> flattenStream(col.stream()))
                .collect(Collectors.toSet());
    }
    
    public static Stream<?> flattenStream(Stream<?> stream) {
        return stream.flatMap(e -> {
            if (e instanceof Collection) {
                return flattenStream(((Collection<?>) e).stream());
            } else {
                return Stream.of(e);
            }
        });
    }
    

另请参阅:

The intersection of all combinations of n sets

Set s1 = Set.of(1,2,3);
Set s2 = Set.of(3,4,5);     
Set union = Stream.concat(s1.stream(),s2.stream()).collect(Collectors.toSet());

s1.addAll(s2;

使用上面内置的 java 库