Java HashSet retainAll() Method

The HashSet.retainAll() method in Java is used to retain only the elements in the HashSet that are contained in a specified collection.

Table of Contents

  1. Introduction
  2. retainAll Method Syntax
  3. Examples
    • Basic Example
    • Real-World Use Case: Retaining Active Usernames
  4. Conclusion

Introduction

The HashSet class in Java is part of the Java Collections Framework and implements the Set interface. A HashSet is used to store unique elements and provides constant-time performance for basic operations like add, remove, contains, and size. The retainAll method is used to retain only those elements in the HashSet that are also contained in a specified collection, effectively performing an intersection operation.

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 HashSet.
  • Returns: true if the HashSet changed as a result of the call (i.e., if any elements were removed); false otherwise.

Examples

Basic Example

In this example, we'll use the retainAll method to retain only the elements in a HashSet that are contained in a specified List.

Example

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

public class HashSetRetainAllExample {
    public static void main(String[] args) {
        // Creating a HashSet of Strings
        HashSet<String> set = new HashSet<>();
        set.add("Java");
        set.add("Python");
        set.add("C");
        set.add("JavaScript");

        // Creating a List of Strings
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("C");

        // Retaining only the elements in the HashSet that are also in the List
        boolean changed = set.retainAll(list);

        // Printing the result of the retain operation and the HashSet after the operation
        System.out.println("Did the HashSet change? " + changed);
        System.out.println("HashSet after retainAll: " + set);
    }
}

Output:

Did the HashSet change? true
HashSet after retainAll: [Java, C]

Real-World Use Case: Retaining Active Usernames

In a web application, you might want to retain only the active usernames in a set by removing those that are not currently active.

Example

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

public class ActiveUsersRetainAllExample {
    public static void main(String[] args) {
        // Creating a HashSet to store current usernames
        HashSet<String> currentUsers = new HashSet<>();
        currentUsers.add("john_doe");
        currentUsers.add("jane_smith");
        currentUsers.add("alice_jones");

        // Creating a List of active usernames
        List<String> activeUsers = new ArrayList<>();
        activeUsers.add("john_doe");
        activeUsers.add("alice_jones");

        // Retaining only the active usernames in the current users set
        boolean changed = currentUsers.retainAll(activeUsers);

        // Printing the result of the retain operation and the current users after the operation
        System.out.println("Did the current users change? " + changed);
        System.out.println("Current users after retainAll: " + currentUsers);
    }
}

Output:

Did the current users change? true
Current users after retainAll: [john_doe, alice_jones]

Example: Retaining Available Inventory Items

In an inventory management system, you might want to retain only the items that are available for sale from the total inventory.

Example

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

public class InventoryRetainAllExample {
    public static void main(String[] args) {
        // Creating a HashSet to store all inventory items
        HashSet<String> inventoryItems = new HashSet<>();
        inventoryItems.add("Laptop");
        inventoryItems.add("Monitor");
        inventoryItems.add("Keyboard");
        inventoryItems.add("Mouse");

        // Creating a List of available items for sale
        List<String> availableItems = new ArrayList<>();
        availableItems.add("Laptop");
        availableItems.add("Mouse");

        // Retaining only the available items in the inventory
        boolean changed = inventoryItems.retainAll(availableItems);

        // Printing the result of the retain operation and the inventory after the operation
        System.out.println("Did the inventory change? " + changed);
        System.out.println("Inventory after retainAll: " + inventoryItems);
    }
}

Output:

Did the inventory change? true
Inventory after retainAll: [Laptop, Mouse]

Example: Retaining Required Skills in a Job Application

In a job application system, you might want to retain only the required skills from an applicant's skill set to check if they match the job requirements.

Example

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

public class SkillsRetainAllExample {
    public static void main(String[] args) {
        // Creating a HashSet to store applicant's skills
        HashSet<String> applicantSkills = new HashSet<>();
        applicantSkills.add("Java");
        applicantSkills.add("Python");
        applicantSkills.add("SQL");
        applicantSkills.add("JavaScript");

        // Creating a List of required skills for the job
        List<String> requiredSkills = new ArrayList<>();
        requiredSkills.add("Java");
        requiredSkills.add("SQL");

        // Retaining only the required skills in the applicant's skill set
        boolean changed = applicantSkills.retainAll(requiredSkills);

        // Printing the result of the retain operation and the applicant's skills after the operation
        System.out.println("Did the applicant's skills change? " + changed);
        System.out.println("Applicant's skills after retainAll: " + applicantSkills);
    }
}

Output:

Did the applicant's skills change? true
Applicant's skills after retainAll: [Java, SQL]

Conclusion

The HashSet.retainAll() method in Java provides a way to retain only the elements in the HashSet that are also contained in a specified collection. This method is useful in various scenarios, such as retaining active usernames, available inventory items, or required skills. By understanding how to use this method, you can efficiently manage and manipulate sets in your Java applications.

Comments