Last Updated : 11 Jul, 2025
In Java, the retainAll() method is used to retain only the elements in a collection that are also present in another collection. It modifies the current collection by removing elements that are not in the specified collection.
Example 1: This example demonstrates how the retainAll() method retains only the common elements between two sets.
Java
// Java Program to demonstrate
// the working of retainAll() with Sets
import java.util.*;
public class Geeks {
public static void main(String[] args)
{
// Create two sets of integers
Set<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> s2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
System.out.println("Set 1: " + s1);
System.out.println("Set 2: " + s2);
// Retain only the elements in
// s1 that are also in s2
s1.retainAll(s2);
System.out.println(
"Modified Set 1 after retainAll: " + s1);
}
}
Set 1: [1, 2, 3, 4, 5] Set 2: [3, 4, 5, 6, 7] Modified Set 1 after retainAll: [3, 4, 5]Syntax of retianAll() Method
boolean retainAll(Collection<?> c)
Example 2: This example demonstrates how the retainAll() method modifies a set by retaining only the common elements with another set, and shows the return value indicating whether the set was modified.
Java
// Java program to demonstrate how retainAll()
// method returns boolean value with Sets
import java.util.*;
public class Geeks {
public static void main(String[] args)
{
// Create two sets of integers
Set<Integer> s1
= new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> s2
= new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
System.out.println("Set 1: " + s1);
System.out.println("Set 2: " + s2);
// Call retainAll and check the return value
boolean b = s1.retainAll(s2);
System.out.println(
"Set 1 after retainAll (common elements): "
+ s1);
System.out.println("Was the set modified? " + b);
// Modify s1 to contain all elements from s2
s1 = new HashSet<>(Arrays.asList(3, 4, 5));
// Now retain elements common between s1 and s2
b = s1.retainAll(s2);
System.out.println(
"Set 1 after retainAll (common elements): "
+ s1);
System.out.println("Was the set modified? " + b);
}
}
Output:
Example 3: This example demonstrates that calling retainAll() with a null collection as a parameter throws a NullPointerException.
Java
// Java Program to demonstrates retainAll()
// method throws NullPointerException
import java.util.*;
public class Geeks {
public static void main(String[] args) {
// Create a set with null values
Set<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, null));
Set<Integer> s2 = null;
s1.retainAll(s2);
}
}
Output:
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