Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Merge two Immutable Sets in Java.? [duplicate]

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() {...}
like image 880
Rahat Avatar asked Apr 03 '20 01:04

Rahat


People also ask

How do I combine Hashsets?

The shortest and most idiomatic way to merge contents of a HashSet<T> object with contents of another HashSet<T> is using the HashSet<T>. UnionWith() method. It modifies the HashSet<T> to contain all elements that are present in itself along with elements in the specified HashSet (or any other IEnumerable in general).

How do you concatenate a collection in Java?

Using the concat() Method. The static method concat() combines two Streams logically by creating a lazily concatenated Stream whose elements are all the elements of the first Stream followed by all the elements of the second Stream.

How do you combine a list of objects in Java?

One way to merge multiple lists is by using addAll() method of java. util. Collection class, which allows you to add the content of one List into another List. By using the addAll() method you can add contents from as many List as you want, it's the best way to combine multiple List.


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();
like image 140
Jason Avatar answered Oct 21 '22 20:10

Jason