What is the Purpose of the retainAll() Method in Java?

What is the Purpose of the retainAll() Method in Java?

In this article, we will explore the retainAll() method in Java, which is a crucial part of the Java Collection Framework. The method is primarily used to manipulate collections and work with data in an efficient way. Let’s dive deep into its purpose, functionality, and real-world applications.

Understanding the retainAll() Method

The retainAll() method is defined in the Collection interface in Java. It is implemented by most of the collection classes like List, Set, and others that implement the Collection interface.

Its primary purpose is to modify the calling collection by retaining only the elements that are also present in the specified collection. In other words, it removes all elements that are not contained in the specified collection.

Method Signature:

boolean retainAll(Collection c);

The method returns true if the calling collection is modified as a result of the operation, and false if it is not.

How the retainAll() Method Works

Let’s break down how the retainAll() method works. Given two collections, the retainAll() method will remove all elements in the calling collection that are not found in the specified collection.

Here is a step-by-step breakdown of how it behaves:

  • The calling collection is compared with the specified collection.
  • Any element in the calling collection that is not present in the specified collection will be removed.
  • The method returns true if any elements were removed, otherwise, it returns false.

Code Example: Using retainAll() in Java

To better understand the retainAll() method, let’s look at a concrete example using a Set and a List.

Example 1: Using retainAll() with a Set


import java.util.HashSet;
import java.util.Set;

public class RetainAllExample {
    public static void main(String[] args) {
        Set set1 = new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(3);
        set1.add(4);

        Set set2 = new HashSet<>();
        set2.add(3);
        set2.add(4);
        set2.add(5);

        // Retaining elements present in both sets
        set1.retainAll(set2);

        System.out.println("After retainAll operation: " + set1);
    }
}
        

In this example, set1 contains the elements 1, 2, 3, 4, and set2 contains the elements 3, 4, 5. After invoking the retainAll() method on set1, only the elements that are present in both set1 and set2 will remain. The output will be:

After retainAll operation: [3, 4]

Example 2: Using retainAll() with a List


import java.util.ArrayList;
import java.util.List;

public class ListRetainAllExample {
    public static void main(String[] args) {
        List list1 = new ArrayList<>();
        list1.add("apple");
        list1.add("banana");
        list1.add("cherry");
        list1.add("date");

        List list2 = new ArrayList<>();
        list2.add("banana");
        list2.add("cherry");

        // Retaining elements that are common in both lists
        list1.retainAll(list2);

        System.out.println("After retainAll operation: " + list1);
    }
}
        

In this second example, list1 contains apple, banana, cherry, date and list2 contains banana, cherry. After calling the retainAll() method on list1, only the common elements banana and cherry will remain in list1. The output will be:

After retainAll operation: [banana, cherry]

When to Use the retainAll() Method?

The retainAll() method is especially useful when you need to filter elements from a collection, keeping only those elements that are present in another collection. Some common use cases are:

  • Intersecting Collections: You can use retainAll() to find the intersection between two collections.
  • Filtering Data: If you need to filter a list based on another reference list, retainAll() provides an efficient way to do so.
  • Eliminating Redundant Data: It can be used to clean up data by retaining only the relevant items.

Things to Keep in Mind

Before using the retainAll() method, consider the following points:

  • Modifies the Original Collection: This method changes the calling collection, so it’s important to make sure you don’t lose important data.
  • Performance: The method may not be efficient for large collections, as it performs a comparison between the elements.
  • Not Suitable for Null Elements: If the specified collection contains null elements, and the calling collection doesn’t, a NullPointerException might occur.

© 2025 Tech Interview Guide. All rights reserved.

Please follow and like us:

Leave a Comment