如何在 Java 中合并两个不可变集。?

Rah*_*hat 6 java collections guava

我正在使用 Guava 的 Immutable 集合。基本上我有两个辅助函数,它们返回 ImmutableSets,它们都包含数据,这些数据是实现公共接口的内部类的实例。但是,我想在实际函数中将两个 Immutable 集合按顺序合并为一个 ImmutableSet。

private static ImmutableSet<Fruit.seedless> helper1(args...) {...}
private static ImmutableSet<Fruit.seeded> helper2(args...) {...}
public ImmutableSet<Fruit> MainFunction() {...}
Run Code Online (Sandbox Code Playgroud)

Jas*_*son 11

这是一个如何组合 2 个或多个 ImmutableSet 对象并创建另一个 ImmutableSet 的示例。这使用 Integer 类型作为参数化类型,因为我无权访问您的 Fruit 类。

        Set<Integer> first = ImmutableSet.of(1);

        Set<Integer> second = ImmutableSet.of(2);

        Set<Integer> third = ImmutableSet.<Integer>builder()
                .addAll(first)
                .addAll(second)
                .build();
Run Code Online (Sandbox Code Playgroud)