Close

Java Collections - ArrayList.retainAll() Examples

[Last Updated: Dec 10, 2025]

Java Collections Java Java API 


Class:

java.util.ArrayList

java.lang.Objectjava.lang.Objectjava.util.AbstractCollectionjava.util.AbstractCollectionjava.util.CollectionCollectionjava.util.AbstractListjava.util.AbstractListjava.util.ListListjava.util.ArrayListjava.util.ArrayListjava.util.ListListjava.util.RandomAccessRandomAccessjava.lang.CloneableCloneablejava.io.SerializableSerializableLogicBig

Methods:

public boolean retainAll (Collection<?> c)

Retains only the elements in this list that are contained in the specified collection. In other words, removes from this list all of its elements that are not contained in the specified collection.




Examples


package com.logicbig.example.arraylist;

import java.util.*;

public class RetainAllExample {

public static void main(String... args) {
// Keep only elements present in another collection
ArrayList<String> list = new ArrayList<>(Arrays.asList("A","B","C","D","E"));
List<String> toKeep = Arrays.asList("B", "D", "F");
list.retainAll(toKeep);
System.out.println("After retainAll: " + list);
}
}

Output

After retainAll: [B, D]
JDK 25




See Also