How to Merge two Immutable Sets in Java.?

Viewed 7484

I'm using Guava's Immutable collections. Basically I have two helper functions that return ImmutableSets both of which contain data that are instances of inner classes that implement a common interface. However, I want to merge the two Immutable sets in order into a single ImmutableSet, in the actual function.

private static ImmutableSet<Fruit.seedless> helper1(args...) {...}
private static ImmutableSet<Fruit.seeded> helper2(args...) {...}
public ImmutableSet<Fruit> MainFunction() {...}
1 Answers

This is an example of how you can combine 2 or more ImmutableSet objects and create another ImmutableSet. This uses the Integer type for the parameterized type because I do not have access to your Fruit class.

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

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

        Set<Integer> third = ImmutableSet.<Integer>builder()
                .addAll(first)
                .addAll(second)
                .build();
Related