Home Java HashSet Methods retainAll() Java HashSet retainAll() Method 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.
Set<String> mine = new HashSet<>(Arrays.asList("Ann", "Bo", "Cy"));
mine.retainAll(Arrays.asList("Bo", "Cy", "Di"));
System.out.println(mine.size()); // 2 Call What 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 // Inherited from java.util.AbstractCollection<E>
public boolean retainAll(Collection<?> c)
// Declared in Set<E> and Collection<E> Parameters Parameter Description c (Collection<?>)The elements to keep. It must not be null.
Return Value Return Value Description trueThe set changed because at least one element was removed. falseEvery element of the set was already in c.
Important
Passing null throws NullPointerException, and an empty collection removes every element. A true result means "something was removed", not "something was kept". The method changes the receiving set, so copy it first if you need the original, and an unmodifiable set throws UnsupportedOperationException.
Compare with Similar Methods The three classic set operations:
Method How 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 1. Intersection 2. Return value 3. Validate input Example 1 — Find Mutual Friends Keep only the names that appear in both friend lists.
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());
}
} mutual: [Bo, Di]
mine still has 4
yours still has 4 How It Works Start from a copy. mutual begins as a copy of mine, so the original list of four friends is not damaged.Two survivors. Only Bo and Di are also in yours; Ann and Cy are removed from the copy.Extras are ignored. Ed and Flo exist only in yours, and retainAll never adds anything.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.
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());
}
} bigger list: false
three of four: true
left: [green, red]
empty argument: true
isEmpty: true How It Works Nothing lost. Red, green, and blue are all in the first argument, so no element is removed and the result is false.Blue is lost. The second argument lacks "blue", so it is removed and the call returns true; "gold" is not added.What is left. Green and red remain, printed in sorted order.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.
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));
}
} chosen: 4 seats
valid: [2, 4] How It Works Duplicates collapse first. The list has five numbers, but 2 appears twice, so the set chosen holds four seats.A built whitelist. The loop fills validSeats with 1 to 5, the only seats that exist.Invalid seats leave. 9 and 7 are not in the whitelist, so retainAll removes them.Result. Seats 2 and 4 survive and are printed in ascending order.Frequently Asked Questions What does HashSet retainAll() do? 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.
How do I find the common elements of two sets in Java? Copy the first set with new HashSet<>(a), then call copy.retainAll(b). The copy holds the intersection.
What happens if I call retainAll() with an empty collection? Every element is removed, so the set becomes empty and the method returns true if the set had elements.
Does retainAll() change the collection I pass in? No. Only the set you call it on can change.
Does retainAll() throw an exception for null? Yes. retainAll(null) throws NullPointerException.
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion