The retainAll() method is a key operation in Java ArrayList
class. It enables you to retain only those elements in your list that are also present in a specified collection, removing all others. This method is essential when you want to extract the intersection (common elements) between your list and another collection for filtering or data management purposes.
What Is the retainAll() Method in ArrayList?
- The
retainAll()
method removes from the list all items not present in the specified collection. - The original list is modified directly: only elements found in the argument collection remain; all others are removed.
- The method returns
true
if any elements were removed (i.e., if the list was changed), otherwisefalse
.
Syntax
public boolean retainAll(Collection<?> c)
Where:
c
: The collection containing the elements to keep in the list.
Parameters
Parameter | Description |
---|---|
c | The collection whose elements are to be retained in the list. |
Return Value
Returns | Description |
---|---|
true | If the list was changed as a result. |
false | If no changes were made (i.e., all elements already present). |
Exceptions
NullPointerException
: If the specified collection is null, or if the list contains null elements and the collection does not permitnull
values.ClassCastException
: If an element in the list is incompatible with the types allowed in the collection.
How Does retainAll() Work Internally?
- The method iterates through the list, removing any elements not found in the provided collection.
- The operation is done in-place: the original list is updated and the result contains only items present in the collection.
Examples of the retainAll() Method
1. Keep Only Common Strings from Two Lists
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.add("Toyota"); ArrayList<String> valid = new ArrayList<>(); valid.add("Volvo"); valid.add("Ford"); valid.add("Mazda"); cars.retainAll(valid); // Output: [Volvo, Ford, Mazda] System.out.println(cars); } }
Only “Volvo”, “Ford”, and “Mazda” are kept, as they are present in the valid
collection.
2. retainAll() with Custom Objects (Ensure equals() Is Overridden)
import java.util.ArrayList; class Fruit { String name; Fruit(String name) { this.name = name; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Fruit)) return false; Fruit other = (Fruit) obj; return name.equals(other.name); } @Override public int hashCode() { return name.hashCode(); } } public class Demo { public static void main(String[] args) { ArrayList<Fruit> fruits = new ArrayList<>(); fruits.add(new Fruit("Apple")); fruits.add(new Fruit("Banana")); ArrayList<Fruit> keepList = new ArrayList<>(); keepList.add(new Fruit("Banana")); fruits.retainAll(keepList); System.out.println(fruits.size()); // Output: 1 } }
Only the “Banana” object remains, as it matches by name due to the overridden equals()
method.
3. Using retainAll() with HashSet
import java.util.ArrayList; import java.util.HashSet; public class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); HashSet<Integer> primes = new HashSet<>(); primes.add(2); primes.add(3); primes.add(5); numbers.retainAll(primes); System.out.println(numbers); // Output: [2, 3] } }
Keeps only the elements present in both the ArrayList
and the HashSet
.
Important Notes
- Only elements present in both the original list and the specified collection are retained; others are deleted.
- The collection argument can be any type implementing the
Collection
interface (e.g.,ArrayList
,HashSet
). - If there are duplicate elements in the original list, those duplicates are preserved only if present in the collection argument.
- The method does not affect the argument collection.
- Both the original list and specified collection are compared using
equals()
for object equality; overrideequals()
for custom objects. - The method does not allow modification if the list or collection is immutable.
Summary
Aspect | Details |
---|---|
Method Purpose | Retain only the elements present in the specified collection |
Syntax | list.retainAll(Collection<?> c) |
Return Value | true if list changed, false otherwise |
Modifies original? | Yes |
Exceptions | NullPointerException , ClassCastException |
Usable With | Any Collection implementing interface |
Typical Use Cases | List intersection, filtering allowed values, cleanup |
Typical Use Cases
- Filtering a list to include only allowed or valid values.
- Finding common elements between two lists or between a list and a set.
- Bulk removal of unwanted items, keeping only those belonging to a specific group.