Union in Java
Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that is returned. When iterating over all the returned sets, each member of set2 that is not also in set1 is iterated over after all of the elements from set1, in that order.
Syntax:
public static <E>
Sets.SetView<E>
union(Set<? extends E> set1,
Set<? extends E> set2)
Return Value: An unchangeable picture of the merging of two sets is what this method returns.
Example 1:
UnionExpl.java
// Guava's Sets.union() function
// is demonstrated in Java
import com.google.common.collect.Sets;
import java.util.Set;
class UnionExpl1 {
// Main code
public static void main(String[] args)
{
// Creating the first set
Set<Integer>
s1 = Sets.newHashSet(1,2,3,4,5);
// Creating the second set
Set<Integer>
s2 = Sets.newHashSet(3,5,7,9);
// Using Guava's Sets.union() method
Set<Integer>
a = Sets.union(s1, s2);
// Displaying the union of set set1 and set2
System.out.println("Set 1: "
+ s1);
System.out.println("Set 2: "
+ s2);
System.out.println("Set 1 union Set 2: "
+ a);
}
}
Output:
Set 1: [1,2,3,4,5]
Set 2: [3,5,7,9]
Set 1 union Set 2: [1,2,3,4,5,7,9]
UnionExpl1.java
// Guava's Sets.union() function
// is demonstrated in Java
import com.google.common.collect.Sets;
import java.util.Set;
class UnionExpl1 {
// Main code
public static void main(String[] args)
{
// Creating the first set
Set<String>
s1 = Sets.newHashSet("J", "a", "v", "a", "t");
// Creating the second set
Set<String>
s2 = Sets.newHashSet("p", "o", "i", "n", "t");
// Using Guava's Sets.union() method
Set<String>
a = Sets.union(s1, s2);
// Displaying the union of set set1 and set2
System.out.println("Set 1: "
+ s1);
System.out.println("Set 2: "
+ s2);
System.out.println("Set 1 union Set 2: "
+ a);
}
}
Output:
Set 1: [J,a,v,a,t]
Set 2: [p,o,i,n,t]
Set 1 union Set 2: [J,a,v,a,t,p,o,i,n,t]