ArrayList retainAll() method example

ArrayList retainAll() retains only the elements in this list that are contained in the specified method argument collection. Rest all elements are removed from the list. This method is exact opposite to removeAll() method.

1. ArrayList retainAll() method

Internally, the retainAll() method iterate over all elements of arraylist. For each element, it pass element to contains() method of argument collection.

If element is not found in argument collection, it re-arranges the index. If element is found, it retains the element inside backing array.

public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, true);
}

private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            // clear to let GC do its work
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}

Method parameter – collection containing elements to be retained from this list.
Method returnstrue if this list changed as a result of the call.
Method throwsClassCastException if the class of an element of this list is incompatible with the specified collection. It may also throw NullPointerException if this list contains a null element and the specified collection does not permit null elements.

2. ArrayList retainAll() example

Java program to retain all elements in a list which are present in specified argument collection, using retainAll() method.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "A", "D", "A"));
        
        System.out.println(alphabets);
        
        alphabets.retainAll(Collections.singleton("A"));
        
        System.out.println(alphabets);
    }
}

Program output.

[A, B, A, D, A]
[A, A, A]

That’s all for the ArrayList retainAll() method in Java.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.