Example 1: Calculate the union of two sets using addAll()
Output
Set1: [2, 4] Set2: [1, 3] Union is: [1, 2, 3, 4]
In the above example, we have created two sets named evenNumbers and numbers. We have implemented the set using the HashSet class. Notice the line,
numbers.addAll(evenNumbers);
Here, we have used the addAll() method to get the union of two sets.
Example 2: Get union of two sets using Guava Library
Output
Programming Languages: [Java, Python] Human Languages: [English, Spanish] Languages: [Java, Python, English, Spanish]
In the above example, we have used the Guava library to get the union of two sets. In order to run this program, you need to implement Guava Library by adding it in your dependency.
Here, we have used the union() method of the Sets class present in the Guava library.