Algorithm
-
Initialize two sets:
- Set A
- Set B
-
Insert elements into sets:
- Populate Set A and Set B with their respective elements.
-
Create a new set for the union:
- Create an empty set C to store the union of A and B.
-
Iterate through Set A:
- For each element in Set A, add it to Set C.
-
Iterate through Set B:
- For each element in Set B, add it to Set C.
-
Result:
- Set C now contains the union of Set A and Set B.
Code Examples
#1 Code Example- Calculate the union of two sets using addAll()
Code -
Java Programming
import java.util.HashSet;
import java.util.Set;
class Main {
public static void main(String[] args) {
// create the first set
Set < Integer> evenNumbers = new HashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("Set1: " + evenNumbers);
// create second set
Set < Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(3);
System.out.println("Set2: " + numbers);
// Union of two sets
numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);
}
}
Copy The Code &
Try With Live Editor
Output
Set1: [2, 4]
Set2: [1, 3]
Union is: [1, 2, 3, 4]
Set2: [1, 3]
Union is: [1, 2, 3, 4]
#2 Code Example- Get union of two sets using Guava Library
Code -
Java Programming
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 set
Set < String> languages1 = new HashSet<>();
languages1.add("Java");
languages1.add("Python");
System.out.println("Programming Languages: " + languages1);
// create second set
Set < String> languages2 = new HashSet<>();
languages2.add("English");
languages2.add("Spanish");
System.out.println("Human Language: " + languages2);
Set < String> unionSet = Sets.union(languages1, languages2);
System.out.println("Union is: " + unionSet);
}
}
Copy The Code &
Try With Live Editor
Output
Programming Languages: [Java, Python]
Human Languages: [English, Spanish]
Languages: [Java, Python, English, Spanish]
Human Languages: [English, Spanish]
Languages: [Java, Python, English, Spanish]
Demonstration
Java Programing Example to Calculate union of two sets-DevsEnv