Java program to calculate the intersection of two sets
Here's an example Java program to calculate the intersection of two sets using the built-in Set data structure and the retainAll() method:
import java.util.HashSet; import java.util.Set; public class SetIntersectionExample { 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 intersection of the sets Set<Integer> intersection = new HashSet<Integer>(set1); intersection.retainAll(set2); // Print the intersection System.out.println("Set1: " + set1); System.out.println("Set2: " + set2); System.out.println("Intersection: " + intersection); } }Sw:ecruoww.theitroad.com
This program creates two sets of integers, adds elements to them, and then calculates the intersection of them using the retainAll() method. The result is a new set that contains only the elements that are in both set1 and set2.
The output of the program will be:
Set1: [1, 2, 3] Set2: [2, 3, 4] Intersection: [2, 3]