Last Updated : 11 Jul, 2025
The retainAll() method in AbstractCollection is used to retain only the elements that are present in a specified collection. It removes all other elements that do not match. This method is useful when performing set intersection operations in Java collections.
Example 1: This example demonstrates how the retainAll() method removes elements that are not present in the second collection.
Java
// Java program to illustrate retainAll() method
import java.util.*;
public class Geeks {
public static void main(String[] args) {
// Creating the first collection
List<String> l1 = new ArrayList<>();
l1.add("one");
l1.add("two");
l1.add("three");
// Creating the second collection
List<String> l2 = new ArrayList<>();
l2.add("three");
l2.add("one");
l2.add("five");
System.out.println("List 1: " + l1);
System.out.println("List 2: " + l2);
// Retaining only the common elements
l2.retainAll(l1);
System.out.println("List 2 after retainAll(): " + l2);
}
}
List 1: [one, two, three] List 2: [three, one, five] List 2 after retainAll(): [three, one]
Explanation: In the above example, list2.retainAll(list1) removes "five" because it is not present in list1. Only "one" and "three" are retained in list2.
Syntax of retainAll() Methodboolean retainAll(Collection c);
Exceptions: This method throws the following exceptions:
Example 2: This example demonstrates what happens when retainAll() is called with a null collection.
Java
// Handling NullPointerException in retainAll()
import java.util.*;
public class Geeks {
public static void main(String[] args) {
// Creating a collection
List<String> l = new ArrayList<>();
l.add("apple");
l.add("banana");
l.add("cherry");
// Display collection before retainAll()
System.out.println("List before retainAll(): " + l);
try {
// Passing null to retainAll()
l.retainAll(null);
} catch (NullPointerException e) {
System.out.println("Exception caught: " + e);
}
}
}
List before retainAll(): [apple, banana, cherry] Exception caught: java.lang.NullPointerException
Explanation: In the above example, the retainAll(null) is not a valid operation, so a NullPointerException is thrown. The exception is caught in the catch block, preventing the program from crashing.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4