Java HashSet retainAll() Method

Java HashSet Java HashSet


Method Overview

retainAll()is JavaHashSetan important method in the class, used to retain elements in the collection that are the same as the specified collection. In other words, it finds the intersection of two sets.

Method Syntax

Example

public boolean retainAll(Collection<?> c)

Method Parameters

  • Collection<?> c: the collection containing the elements to be retained
  • Return value: ifHashSetthe collection is changed by the call, it returnstrue, otherwise returnsfalse

How It Works

Basic Functionality

retainAll()The method modifies the currentHashSetcollection so that it retains only the elements that are the same as the specified collectionc. All elements not in the specified collectioncwill be removed from the currentHashSetcollection.

Algorithm Complexity

The time complexity of this method is usually O(n), where n is the size of the collection, because it needs to check whether each element in the current collection exists in the specified collection.


Usage Examples

Example 1: Basic Usage

Example

import java.util.HashSet;

public class RetainAllExample {
    public static void main(String[] args) {
        // Create the first HashSet
        HashSet<String> set1 = new HashSet<>();
        set1.add("Apple");
        set1.add("Banana");
        set1.add("Orange");
       
        // Create the second HashSet
        HashSet<String> set2 = new HashSet<>();
        set2.add("Banana");
        set2.add("Grape");
       
        // Retain elements in set1 that are the same as those in set2
        boolean changed = set1.retainAll(set2);
       
        System.out.println("Is set1 modified: " + changed);  // Output: true
        System.out.println("set1 after retain: " + set1);  // Output: [Banana]
    }
}

Example 2: No Common Elements

Example

import java.util.HashSet;

public class NoCommonElements {
    public static void main(String[] args) {
        HashSet<Integer> numbers1 = new HashSet<>();
        numbers1.add(1);
        numbers1.add(2);
        numbers1.add(3);
       
        HashSet<Integer> numbers2 = new HashSet<>();
        numbers2.add(4);
        numbers2.add(5);
       
        boolean changed = numbers1.retainAll(numbers2);
       
        System.out.println("Is the collection modified: " + changed);  // Output: true
        System.out.println("numbers1 after retain: " + numbers1);  // Output: []
    }
}

Notes

1. Set Modification

  • If callingretainAll()the collection does not change after the call (i.e., it is already the intersection of the two sets), the method will returnfalse
  • If the specified collectioncis empty, the current collection will be cleared.

2. Concurrent Modification

If you callretainAll()the method while iterating over the collection, it may throwConcurrentModificationException. You should complete the collection modification operation before iterating.

3. Null Value Handling

  • If the current collection allows null values but the parameter collection does not, then callingretainAll()will remove null values afterwards.
  • If the parameter collection is null, it will throwNullPointerException

Practical Use Cases

1. Data Filtering

When you need to filter a subset that meets specific conditions from a large data set, you can useretainAll()the method.

2. Permission Control

In a permission system, this method can be used to find the intersection of all permissions owned by a user and the permissions required by a role.

3. Data Analysis

In data analysis, find the elements common to two data sets.


Comparison with Other Methods

Method Function Whether to modify the original collection Meaning of Return Value
retainAll() Retains elements that are the same as the specified collection Yes Whether the collection is modified
removeAll() Removes elements that are the same as the specified collection Yes Whether the collection is modified
containsAll() Checks whether it contains all elements of the specified collection no Whether all are contained
addAll() Adds all elements of the specified collection Yes Whether the collection is modified

Performance Optimization Suggestions

  1. If you frequently perform set intersection operations, consider using a library optimized specifically for set operations.
  2. For large collections, you can first convert the smaller collection into aHashSetHashSet to improve lookup efficiency.
  3. In a multithreaded environment, useCollections.synchronizedSet()wrapped collections.

Summary

HashSetofretainAll()The method is a powerful collection operation tool that can conveniently implement set intersection functionality. Understanding its working principle and characteristics can help developers handle collection data more efficiently. In actual development, you should choose the appropriate collection operation method according to specific needs, and pay attention to its performance impact and thread safety.

Java HashSet Java HashSet

Other Extensions