Java program to calculate union of two sets
https://www.theitroad.com
Here's an example Java program to calculate the union of two sets using the built-in Set data structure and the addAll() method:
import java.util.HashSet;
import java.util.Set;
public class SetUnionExample {
public static void main(String[] args) {
// Create two sets of integers
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
// Add elements to the sets
set1.add(1);
set1.add(2);
set1.add(3);
set2.add(2);
set2.add(3);
set2.add(4);
// Calculate the union of the sets
Set<Integer> union = new HashSet<Integer>(set1);
union.addAll(set2);
// Print the union
System.out.println("Set1: " + set1);
System.out.println("Set2: " + set2);
System.out.println("Union: " + union);
}
}
This program creates two sets of integers, adds elements to them, and then calculates the union of them using the addAll() method. The result is a new set that contains all the elements from both set1 and set2, with no duplicates.
The output of the program will be:
Set1: [1, 2, 3] Set2: [2, 3, 4] Union: [1, 2, 3, 4]
