Java Program To Find The Intersection Of Two HashSets
Chapter:
Miscellaneous
Last Updated:
07-10-2023 07:05:00 UTC
Program:
/* ............... START ............... */
import java.util.HashSet;
import java.util.Set;
public class IntersectionOfHashSets {
public static void main(String[] args) {
// Create two HashSet collections
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
// Add elements to the first HashSet
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(4);
// Add elements to the second HashSet
set2.add(3);
set2.add(4);
set2.add(5);
set2.add(6);
// Find the intersection of the two HashSet collections
set1.retainAll(set2);
// Display the intersection
System.out.println("Intersection of HashSet 1 and HashSet 2:");
for (Integer element : set1) {
System.out.println(element);
}
}
}
/* ............... END ............... */
Output
Intersection of HashSet 1 and HashSet 2:
3
4
In this example, the program found that the elements 3 and 4 are common to both
HashSet collections, and it displayed them as the intersection.
Notes:
-
In this program, we first create two HashSet collections named set1 and set2. We add some elements to both sets. Then, we use the retainAll() method on set1 to find the intersection with set2. Finally, we iterate over the elements in the intersection and print them to the console.
- When you run this program, it will display the elements that are common to both HashSet collections, which in this example are the elements 3 and 4.
Tags
Java program to find the intersection of two HashSets #How to find the intersection of Hashset in Java? #Get the intersection of two sets in Java