In Java, retainAll(c) keeps only the elements of an ArrayList that are also contained in the collection c and removes all others.
It is the list version of an intersection. Duplicates in the list are kept as long as their value is in c, and the kept elements stay in their original order. It is the opposite of removeAll(c).
An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe.
Syntax
Pass the collection of values to keep.
Java
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "a", "c"));
list.retainAll(Arrays.asList("a", "c")); // true, list = [a, a, c]
list.retainAll(Arrays.asList("a", "c")); // false, nothing more to remove
Call
What it does
list.retainAll(c)
Keeps only the elements that c contains.
list.retainAll(Collections.emptyList())
Removes everything (clear() is clearer).
new ArrayList<>(a) then retainAll(b)
An intersection that leaves a unchanged.
list.removeAll(c)
The opposite: removes the elements that c contains.
Like removeAll, it calls c.contains() once per element, so use a HashSet for c when it is large.
Library declarations
Java
// java.util.ArrayList<E>
public boolean retainAll(Collection<?> c)
// Declared in Collection<E> and List<E>
Parameters
Parameter
Description
c (Collection<?>)
The values to keep. Must not be null.
Return Value
Return Value
Description
boolean
true if at least one element was removed; otherwise false.