Java ArrayList retainAll() Method

The ArrayList.retainAll() method in Java is used to retain only the elements in the ArrayList that are contained in the specified collection. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality. Additionally, we will cover a real-world use case to illustrate its application.

Table of Contents

  1. Introduction
  2. retainAll Method Syntax
  3. How It Works
  4. Examples
    • Retaining Common Elements
    • Handling No Common Elements
  5. Real-World Use Case
  6. Conclusion

Introduction

The ArrayList.retainAll() method is part of the ArrayList class in Java. It allows you to filter the list so that only elements also present in the specified collection are retained. This method is useful for finding common elements between two collections or filtering a list based on another collection.

retainAll Method Syntax

The syntax for the retainAll method is as follows:

public boolean retainAll(Collection<?> c)
  • c: The collection containing elements to be retained in the list.
  • The method returns true if the list was modified as a result of the call, and false otherwise.

How It Works

When you use the retainAll(Collection<?> c) method, the ArrayList iterates over its elements and retains only those that are also present in the specified collection. The method modifies the list in-place and returns true if any elements were removed, or false if no elements were removed.

Examples

Retaining Common Elements

The retainAll method can be used to retain only the elements that are present in another collection.

Example

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

public class RetainAllExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Orange", "Grapes"));
        List<String> toRetain = new ArrayList<>(Arrays.asList("Banana", "Grapes", "Pineapple"));

        // Retain only elements that are also in the toRetain list
        boolean isModified = list.retainAll(toRetain);

        System.out.println("List after retainAll: " + list);
        System.out.println("Was the list modified? " + isModified);
    }
}

Output:

List after retainAll: [Banana, Grapes]
Was the list modified? true

Handling No Common Elements

If there are no common elements between the ArrayList and the specified collection, the retainAll method will remove all elements from the list.

Example

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

public class RetainAllNoCommonElementsExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Orange"));
        List<String> toRetain = new ArrayList<>(Arrays.asList("Grapes", "Pineapple"));

        // Attempt to retain elements with no common elements in the toRetain list
        boolean isModified = list.retainAll(toRetain);

        System.out.println("List after retainAll: " + list);
        System.out.println("Was the list modified? " + isModified);
    }
}

Output:

List after retainAll: []
Was the list modified? true

Real-World Use Case

Filtering Active Users from a List

In an application where you manage a list of users, you might want to retain only the active users based on another collection of active user IDs. The retainAll() method can be used to filter the list of users to keep only those who are active.

Example

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

class User {
    String id;
    String name;

    User(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return id + ": " + name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id.equals(user.id);
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}

public class UserManagement {
    public static void main(String[] args) {
        List<User> users = new ArrayList<>(Arrays.asList(
                new User("1", "Alice"),
                new User("2", "Bob"),
                new User("3", "Charlie"),
                new User("4", "Dave")
        ));
        List<User> activeUsers = new ArrayList<>(Arrays.asList(
                new User("2", "Bob"),
                new User("4", "Dave")
        ));

        // Retain only active users
        boolean isModified = users.retainAll(activeUsers);

        System.out.println("Active users after retainAll:");
        users.forEach(System.out::println);
        System.out.println("Was the list modified? " + isModified);
    }
}

Output:

Active users after retainAll:
2: Bob
4: Dave
Was the list modified? true

Conclusion

The ArrayList.retainAll() method in Java provides a way to retain only the elements in an ArrayList that are contained in a specified collection. By understanding how to use this method, you can efficiently filter and clean up lists in your Java applications. This method is particularly useful in real-world applications such as retaining active users, finding common elements between collections, and managing subsets of data.

Leave a Comment

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

Scroll to Top