Java HashSet retainAll() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In Java, retainAll(c) removes from a HashSet every element that is not contained in the collection c. What stays is the intersection: the elements both collections share.

It returns true if the set lost at least one element. Only the receiving set changes; the argument is just read.

An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety.

Syntax

One argument: the collection of elements to keep.

Java
Set<String> mine = new HashSet<>(Arrays.asList("Ann", "Bo", "Cy"));
mine.retainAll(Arrays.asList("Bo", "Cy", "Di"));
System.out.println(mine.size());   // 2
CallWhat it does
a.retainAll(b)Keeps only the elements of a that are also in b.
new HashSet<>(a).retainAll(b)Computes the intersection on a copy.
a.retainAll(menu)Whitelist: drops any input that is not on the allowed list.
a.retainAll(new ArrayList<>())Empty argument: removes everything.

For each element of the set, retainAll asks the argument contains(). Pass a HashSet instead of a List when both collections are large.

Library declarations
Java
// Inherited from java.util.AbstractCollection<E>
public boolean retainAll(Collection<?> c)

// Declared in Set<E> and Collection<E>

Parameters

ParameterDescription
c (Collection<?>)The elements to keep. It must not be null.

Return Value

Return ValueDescription
trueThe set changed because at least one element was removed.
falseEvery element of the set was already in c.

Compare with Similar Methods

The three classic set operations:

MethodHow it differs
removeAll(c)The opposite: removes the shared elements (difference).
addAll(c)Adds all elements (union).
containsAll(c)Only tests whether all of c is present; changes nothing.
removeIf(test)Removes by a condition instead of by membership.

Java Examples

Example 1 — Find Mutual Friends

Keep only the names that appear in both friend lists.

Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class HashSetRetainAllDemo {
    public static void main(String[] args) {
        Set<String> mine = new HashSet<>(Arrays.asList("Ann", "Bo", "Cy", "Di"));
        Set<String> yours = new HashSet<>(Arrays.asList("Bo", "Di", "Ed", "Flo"));

        Set<String> mutual = new HashSet<>(mine);
        mutual.retainAll(yours);

        System.out.println("mutual: " + new TreeSet<>(mutual));
        System.out.println("mine still has " + mine.size());
        System.out.println("yours still has " + yours.size());
    }
}

How It Works

  1. Start from a copy. mutual begins as a copy of mine, so the original list of four friends is not damaged.
  2. Two survivors. Only Bo and Di are also in yours; Ann and Cy are removed from the copy.
  3. Extras are ignored. Ed and Flo exist only in yours, and retainAll never adds anything.
  4. Both inputs unchanged. The two original sets keep four elements each.

Example 2 — Return Value: Did Anything Get Removed?

Call retainAll four times on one set and watch the boolean and the contents.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class HashSetRetainAllResult {
    public static void main(String[] args) {
        Set<String> allowed = new HashSet<>(Arrays.asList("red", "green", "blue"));

        System.out.println("bigger list: " + allowed.retainAll(Arrays.asList("red", "green", "blue", "pink")));
        System.out.println("three of four: " + allowed.retainAll(Arrays.asList("red", "green", "gold")));
        System.out.println("left: " + new TreeSet<>(allowed));

        System.out.println("empty argument: " + allowed.retainAll(new ArrayList<String>()));
        System.out.println("isEmpty: " + allowed.isEmpty());
    }
}

How It Works

  1. Nothing lost. Red, green, and blue are all in the first argument, so no element is removed and the result is false.
  2. Blue is lost. The second argument lacks "blue", so it is removed and the call returns true; "gold" is not added.
  3. What is left. Green and red remain, printed in sorted order.
  4. Empty means wipe. No element is in an empty list, so every element is removed (true) and isEmpty() becomes true.

Example 3 — Keep Only Valid Seat Numbers

Drop every chosen seat that is not in the set of seats that actually exist.

Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class HashSetRetainAllValidate {
    public static void main(String[] args) {
        Set<Integer> validSeats = new HashSet<>();
        for (int seat = 1; seat <= 5; seat++) {
            validSeats.add(seat);
        }

        Set<Integer> chosen = new HashSet<>(Arrays.asList(2, 9, 4, 2, 7));
        System.out.println("chosen: " + chosen.size() + " seats");

        chosen.retainAll(validSeats);
        System.out.println("valid: " + new TreeSet<>(chosen));
    }
}

How It Works

  1. Duplicates collapse first. The list has five numbers, but 2 appears twice, so the set chosen holds four seats.
  2. A built whitelist. The loop fills validSeats with 1 to 5, the only seats that exist.
  3. Invalid seats leave. 9 and 7 are not in the whitelist, so retainAll removes them.
  4. Result. Seats 2 and 4 survive and are printed in ascending order.

Frequently Asked Questions

It keeps only the elements that are also in the collection you pass in and removes all others. It returns true if the set changed.
Copy the first set with new HashSet<>(a), then call copy.retainAll(b). The copy holds the intersection.
Every element is removed, so the set becomes empty and the method returns true if the set had elements.
No. Only the set you call it on can change.
Yes. retainAll(null) throws NullPointerException.

Next: size()

Count the elements in the set.

size() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful