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