![]() |
VOOZH | about |
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.
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.
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.
There are multiple methods to find the Intersection of HashSets in Java as mentioned below:
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.
public boolean retainAll(Collection<?> C)
where, it accepts object implementing the Collection Interface. It returns true if the object value is changed.
Set s1: [1, 3, 5, 7] Set s2: [3, 6, 7, 8] Intersection set is: [3, 7]
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.
Set s1: [1, 3, 5, 7] Set s2: [3, 6, 7, 8] Intersection set is: [3, 7]
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.
Set s1: [1, 3, 5, 7] Set s2: [3, 6, 7, 8] Intersection set is: [3, 7]
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.
Output:
Set s1: [1, 3, 5, 7]
Set s2: [3, 6, 7, 8]
Intersection set is: [3, 7]
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.
Output:
Set s1: [1, 3, 5, 7]
Set s2: [3, 6, 7, 8]
Intersection set is: [3, 7]