Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • Toggle search form

Java ArrayList retainAll() Method

Posted on July 24, 2025July 24, 2025 By Admin No Comments on Java ArrayList retainAll() Method

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), otherwise false.

Syntax

public boolean retainAll(Collection<?> c)

Where:

  • c: The collection containing the elements to keep in the list.

Parameters

ParameterDescription
cThe collection whose elements are to be retained in the list.

Return Value

ReturnsDescription
trueIf the list was changed as a result.
falseIf 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 permit null 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; override equals() for custom objects.
  • The method does not allow modification if the list or collection is immutable.

Summary

AspectDetails
Method PurposeRetain only the elements present in the specified collection
Syntaxlist.retainAll(Collection<?> c)
Return Valuetrue if list changed, false otherwise
Modifies original?Yes
ExceptionsNullPointerException, ClassCastException
Usable WithAny Collection implementing interface
Typical Use CasesList 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.
Java Tags:Java-ArrayList, Java-ArrayList-Method, Java-Collections

Post navigation

Previous Post: Java ArrayList replaceAll() Method
Next Post: Java ArrayList set() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java ArrayList
  • Java ArrayList Methods
  • Java ArrayList add() Method
  • Java ArrayList addAll() Method
  • Java ArrayList clear() Method
  • Java ArrayList clone() Method
  • Java ArrayList contains() Method
  • Java ArrayList ensureCapacity() Method
  • Java ArrayList forEach() Method
  • Java ArrayList get() Method
  • Java ArrayList indexOf() Method
  • Java ArrayList isEmpty() Method
  • Java ArrayList iterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList listIterator() Method
  • Java ArrayList remove() Method
  • Java ArrayList removeAll() Method
  • Java ArrayList removeIf() Method
  • Java ArrayList replaceAll() Method
  • Java ArrayList retainAll() Method
  • Java ArrayList set() Method
  • Java ArrayList size() Method
  • Java ArrayList sort() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList subList() Method
  • Java ArrayList toArray() Method
  • Java ArrayList trimToSize() Method

Recent Posts

  • Java ArrayList trimToSize() Method
  • Java ArrayList toArray() Method
  • Java ArrayList subList() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList sort() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme