Java List retainAll()

In Java, the ArrayList.retainAll() retains only those elements in this list that are contained in the specified collection. Rest all elements are removed from the list. This method is exactly the opposite to removeAll() method.

1. Syntax

The syntax to use the retainAll() method is:

boolean retainAll(Collection<?> c);

Method Argument – a 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. Java Program to use retainAll() Method

In the following program, we have two lists. When we call list1.retainAll(list2), the program leaves only those elements in list1 that are also present in list2.

List<Integer> list1 = new ArrayList<>(Stream.of(1, 2, 3, 4, 5).toList());
List<Integer> list2 = new ArrayList<>(Stream.of(1, 2, 3, 6, 7).toList());

list1.retainAll(list2);

System.out.println(list1);  //[1, 2, 3]
System.out.println(list2);  //[1, 2, 3, 6, 7]

3. How retainAll() Works?

Internally, the retainAll() iterates over all elements of the list. For each element, it passes the element to contains() method of argument collection.

If the element is not found in the argument collection, it re-arranges the index. If the element is found, it retains the element inside the 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;
}

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

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

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.