Open In App

Find the Intersection of Two HashSets in Java

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Intersection_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.

Methods Find the Intersection of Two HashSets in Java

There are multiple methods to find the Intersection of HashSets in Java as mentioned below:

  1. using retainAll() method
  2. using Java 8 Stream API
  3. using loops
  4. using Google Guava library
  5. 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);
    }
}


Output

Set 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);
    }
}


Output

Set 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);
    }
}


Output

Set 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]



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads