Find the Intersection of Two HashSets in Java
Last Updated :
28 Apr, 2025
HashSets is a type of Collection in Java that cannot contain any duplicate values. It is often used when we need to maintain a unique data set in our application, it uses hashing internally to store the elements in it, so operations like searching, insertion, and deletion take only a constant amount of time with HashSets. In this article, we will learn methods to find the Intersection of Two HashSets in Java.
Intersection of Two HashSets
In HashSets, different mathematical set operations can be performed, these include union, intersection, and difference. In particular, intersection is a type of set operation where the resultant set will contain elements that are present in both of the sets.
.png)
In the above image we can see how it will look like in a Venn diagram, there are different methods to achieve the intersection between HashSets in java.
Methods Find the Intersection of Two HashSets in Java
There are multiple methods to find the Intersection of HashSets in Java as mentioned below:
- using retainAll() method
- using Java 8 Stream API
- using loops
- using Google Guava library
- using Apache Commons Collections library.
1. retainAll() method
retainAll is a method under Set Interface of Java Collections API, retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
Syntax:
public boolean retainAll(Collection<?> C)
where, it accepts object implementing the Collection Interface. It returns true if the object value is changed.
Java
// Java program to intersect hashsets
// using retainAll method
import java.util.HashSet;
import java.util.Set;
// Driver class
class GFG {
// Driver method
public static void main(String[] args)
{
// Creating 2 hashsets and adding
// some values using add() method
Set<Integer> s1 = new HashSet<>();
s1.add(1);
s1.add(3);
s1.add(5);
s1.add(7);
Set<Integer> s2 = new HashSet<>();
s2.add(3);
s2.add(6);
s2.add(7);
s2.add(8);
// Create a intersection object from any hashset
// use retainAll() method to retain only the values
// present in both the sets.
Set<Integer> intersection = new HashSet<>(s1);
// pass the another object to retain the values
intersection.retainAll(s2);
System.out.println("Set s1: " + s1);
System.out.println("Set s2: " + s2);
System.out.println("Intersection set is: "
+ intersection);
}
}
OutputSet s1: [1, 3, 5, 7]
Set s2: [3, 6, 7, 8]
Intersection set is: [3, 7]
2. Java 8 Stream API
In this method, we will use the Java 8 Stream API, Streams is a powerful feature to manipulate Collection of objects in Java, various functions can be pipelined to implement complex functionality to arrive at the desired result. Here, creates a stream from a set and pass the contains function from another set as a filter to find the intersected values.
Java
// Java program to intersect hashsets
// using Streams
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
// Driver class
class GFG {
// Driver function
public static void main(String[] args)
{
// Creating 2 hashsets and adding
// some values using add() method
Set<Integer> s1 = new HashSet<>();
s1.add(1);
s1.add(3);
s1.add(5);
s1.add(7);
Set<Integer> s2 = new HashSet<>();
s2.add(3);
s2.add(6);
s2.add(7);
s2.add(8);
// Create a intersection set using streams
// using filter with s2.contains() method
// collect that into a set with Collectors.toSet()
Set<Integer> intersection
= s1.stream()
.filter(s2::contains)
.collect(Collectors.toSet());
System.out.println("Set s1: " + s1);
System.out.println("Set s2: " + s2);
System.out.println("Intersection set is: "
+ intersection);
}
}
OutputSet s1: [1, 3, 5, 7]
Set s2: [3, 6, 7, 8]
Intersection set is: [3, 7]
3. Java Loops
In this method, we can use loops to iterate over a set and check whether it is present in another set, if it is present in another set too then it should be in the intersect HashSet, so add it to the set using add() method.
Java
// Java program to intersect hashsets
// using loops
import java.util.HashSet;
import java.util.Set;
// Driver class
class GFG {
// Driver function
public static void main(String[] args)
{
// Creating 2 hashsets and adding
// some values using add() method
Set<Integer> s1 = new HashSet<>();
s1.add(1);
s1.add(3);
s1.add(5);
s1.add(7);
Set<Integer> s2 = new HashSet<>();
s2.add(3);
s2.add(6);
s2.add(7);
s2.add(8);
// create a intersection set object
Set<Integer> intersection = new HashSet<>();
// iterate over a set here, s1
for (int val : s1) {
// check its presence using contains in s2
if (s2.contains(val)) {
// add it to intersection set
intersection.add(val);
}
}
System.out.println("Set s1: " + s1);
System.out.println("Set s2: " + s2);
System.out.println("Intersection set is: "
+ intersection);
}
}
OutputSet s1: [1, 3, 5, 7]
Set s2: [3, 6, 7, 8]
Intersection set is: [3, 7]
4. Guava library
In this method, we can use a library like Guava by Google, which has a utility function called Sets.intersection() that takes two sets as parameters and provides the resultant intersection set.
Java
// Java program to intersect hashsets
// using Google guava library
import com.google.common.collect.Sets;
import java.util.HashSet;
import java.util.Set;
class GFG {
public static void main(String[] args)
{
// Creating 2 hashsets and adding
// some values using add() method
Set<Integer> s1 = new HashSet<>();
s1.add(1);
s1.add(3);
s1.add(5);
s1.add(7);
Set<Integer> s2 = new HashSet<>();
s2.add(3);
s2.add(6);
s2.add(7);
s2.add(8);
// Sets class function from guava library
Set<Integer> intersection
= Sets.intersection(s1, s2);
System.out.println("Set s1: " + s1);
System.out.println("Set s2: " + s2);
System.out.println("Intersection set is: "
+ intersection);
}
}
Output:
Set s1: [1, 3, 5, 7]
Set s2: [3, 6, 7, 8]
Intersection set is: [3, 7]
5. Apache Commons Collection library
In this method, SetUtils from Apache Commons Collection library can be used to create an intersection set object. SetUtils provides an intersection method to accept two sets and provides the intersection values of it.
Java
// Java program to intersect hashsets
// using apache commons collections
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.collections4.SetUtils;
class GFG {
public static void main(String[] args)
{
// Creating 2 hashsets and adding
// some values using add() method
Set<Integer> s1 = new HashSet<>();
s1.add(1);
s1.add(3);
s1.add(5);
s1.add(7);
Set<Integer> s2 = new HashSet<>();
s2.add(3);
s2.add(6);
s2.add(7);
s2.add(8);
// SetUtils intersection from apache
// commons collection library
Set<Integer> intersection
= SetUtils.intersection(s1, s2);
System.out.println("Set s1: " + s1);
System.out.println("Set s2: " + s2);
System.out.println("Intersection set is: "
+ intersection);
}
}
Output:
Set s1: [1, 3, 5, 7]
Set s2: [3, 6, 7, 8]
Intersection set is: [3, 7]
Similar Reads
How to Find the Intersection of Two Strings in Java?
We know that the Strings are a collection of characters so if we want to find the intersection of two Strings the simple way is we can compare each character of the first String with the characters of the Second String. Example to Find the Intersection of Two Strings in JavaThere are two strings ava
2 min read
Java Program to Find the Intersection Between Two Collection
Collection means a set of different classes and interfaces are group together into a single unit that has similar functions are called collection and framework we know very that provides a predefined architecture to represents and manipulate collections in java. Here we will be discussing discuss ou
4 min read
How to Find the Intersection and Union of Two PriorityQueues in Java?
In Java, PriorityQueue is an implementation of the Queue Interface. It can be used to provide a way to store the elements in a queue based on their priority basis. This means high-priority elements can store first compared to lower-priority elements in the queue. In this article, we will be learning
2 min read
How to Iterate HashSet in Java?
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.Methods to Ite
3 min read
How to Iterate Over a HashSet Without an Iterator in Java?
In Java, we can iterate over a HashSet without using an Iterator. For this, we need two methods. We can directly loop through the elements of the HashSet. In this article, we will discuss the two methods to iterate over a HashSet without using Iterator. Program to Iterate over a HashSet without an I
2 min read
Java Program For Finding Intersection Of Two Sorted Linked Lists
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory â the original lists should not be changed. Example: Input: First linked list: 1->2->3->4->6 Second linked list be 2-
5 min read
Java Program For Finding Intersection Point Of Two Linked Lists
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge. Above diagram shows an example with two linked lists havi
7 min read
How to Convert a HashSet to JSON in Java?
In Java, a HashSet is an implementation of the Set interface that uses a hash table to store elements. It allows fast lookups and does not allow duplicate elements. Elements in a HashSet are unordered and can be of any object type. In this article, we will see how to convert a HashSet to JSON in Jav
2 min read
How to Iterate Through HashTable in Java?
HashTable is an underlying data structure where the insertion order in HashTable is not preserved, and it is based on the hashcode of keys. Duplicates keys are not allowed, but values can be duplicated. Heterogeneous objects are allowed for both keys and values. Value null is not allowed for both ke
8 min read
How to Convert List of Lists to HashSet in Java?
In Java, Collections like lists, and sets play a crucial role in converting and manipulating the data efficiently. The Conversion of a List of Lists into a HashSet is mainly used to Remove Duplicates and ensures the programmer maintains the unique data of elements. Example to Convert List of Lists t
2 min read