English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to calculate the union of two sets in Java.
To understand this example, you should understand the followingJava ProgrammingTopic:
import java.util.HashSet; import java.util.Set; class Main { public static void main(String[] args) { //Create the first collection Set<Integer> evenNumbers = new HashSet<>(); evenNumbers.add(2); evenNumbers.add(4); System.out.println("Set1: " + evenNumbers); //Create the second collection Set<Integer> numbers = new HashSet<>(); numbers.add(1); numbers.add(3); System.out.println("Set2: " + numbers); //The union of the two sets numbers.addAll(evenNumbers); System.out.println("The union of the two sets: " + numbers); } }
Output Result
Set1: [2, 4] Set2: [1, 3] The union of the two sets: [1, 2, 3, 4]
In the above example, we created two collections named evenNumbers and numbers. We implemented the collection using the HashSet class. Note this line,
numbers.addAll(evenNumbers);
In this example, we use the addAll() method to obtain the union of two sets.
import java.util.HashSet; import java.util.Set; import com.google.common.collect.Sets; class Main { public static void main(String[] args) { //Create the first collection Set<String> languages1 = new HashSet<>(); languages1.add("Java"); languages1.add("Python"); System.out.println("Programming languages: " + languages1); //Create the second collection Set<String> languages2 = new HashSet<>(); languages2.add("English"); languages2.add("Spanish"); System.out.println("Human Languages: ", + languages2); Set<String> unionSet = Sets.union(languages1, languages2); System.out.println("The union is: ", + unionSet); } }
Output Result
Programming Languages: [Java, Python] Human Languages: [English, Spanish] The union is: [Java, Python, English, Spanish]
In the above example, we useGuava LibraryTo run this program, you need to implement it by adding the Guava library to the dependencies.
Here, we use the union() method of the Sets class that exists in the Guava library.