Java intersection of Sets

If you need to get only the elements which are common for two sets you can use the method retainAll. The documentation for this method states:

Method signature: boolean retainAll(Collection<?> c)

Description: 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.

Parameters: c – collection containing elements to be retained in this set

Returns: true if this set changed as a result of the call”

Important: the objects in the sets must overwrite equals() and hashCode() methods to work with retainAll. We must give a proper implementation of equals() and hashCode() related to the class. In my example, I am using String which already has equals() and hashCode() implemented to be effective.

In the program, we have two sets (set a and set b) with strings. We get the intersection of all the common elements of set a and set b in Set result.

import java.util.HashSet;
import java.util.Set;

public class MainIntersection {

    public static void main(String[] args) {
        Set<String> a = Set.of("A", "B", "C", "D", "E");
        Set<String> b = Set.of("M", "B", "N", "D", "O");
        // The intersection between the two sets is "B" and "D"

        // use copy constructor to get all values from Set "a"
        Set<String> result = new HashSet<>(a);

        // !! Pay attention that here "result" will be modified
        // Retains only the elements in this set
        // that are contained in the specified collection
        result.retainAll(b);

        System.out.println(result);
    }
}

Output:

[B, D]

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.