Java HashSet removeAll() Method

Java HashSet Java HashSet


removeAll()The method is an important method in the JavaHashSetclass, used to remove from the current collection all elements that are the same as those in the specified collection. This method is inherited from thejava.util.AbstractSetclass, and is implemented inHashSet.

Method Syntax

public boolean removeAll(Collection<?> c)

Method Parameters

removeAll()The method accepts one parameter:

  • Collection<?> c: A collection containing the elements to be removed from the current collection. This parameter can be any object that implements theCollectioninterface, such asArrayList、LinkedListor anotherHashSet。

Return Value

This method returns a boolean value:

  • true: If the current collection was changed as a result of calling this method (i.e., at least one element was successfully removed)
  • false: If the current collection did not change (i.e., none of the elements in the specified collection exist in the current collection)

Detailed Method Function Explanation

removeAll()The method performs the following operations:

  1. Iterates through all elements in the parameter collectionc
  2. Checks whether the currentHashSetcontains these elements
  3. If they exist, removes these elements from the currentHashSet
  4. As long as at least one element is removed, it returnstrue; otherwise it returnsfalse

Usage Examples

Basic Usage Example

Example

import java.util.HashSet;

public class RemoveAllExample {
    public static void main(String[] args) {
        // Create the first HashSet
        HashSet<String> set1 = new HashSet<>();
        set1.add("Apple");
        set1.add("Banana");
        set1.add("Orange");
        set1.add("Grape");
       
        // Create the second HashSet
        HashSet<String> set2 = new HashSet<>();
        set2.add("Banana");
        set2.add("Grape");
        set2.add("Watermelon");
       
        System.out.println("set1 initial content: " + set1);
        System.out.println("set2 content: " + set2);
       
        // Use the removeAll() method
        boolean isChanged = set1.removeAll(set2);
       
        System.out.println("set1 content after calling removeAll(): " + set1);
        System.out.println("Whether the collection was modified: " + isChanged);
    }
}

Output result:

set1 初始内容: [Apple, Banana, Orange, Grape]
set2 内容: [Banana, Grape, Watermelon]
调用 removeAll() 后 set1 的内容: [Apple, Orange]
集合是否被修改: true

When No Elements Are Removed

Example

HashSet<Integer> numbers = new HashSet<>(Arrays.asList(1, 2, 3, 4));
HashSet<Integer> toRemove = new HashSet<>(Arrays.asList(5, 6));

System.out.println("Initial collection: " + numbers);
boolean result = numbers.removeAll(toRemove);
System.out.println("After calling removeAll(): " + numbers);
System.out.println("Return value: " + result);

Output result:

初始集合: [1, 2, 3, 4]
调用 removeAll() 后: [1, 2, 3, 4]
返回值: false

Notes

  1. Concurrent modification: If you use theremoveAll()method while iterating over the collection, it may throwConcurrentModificationException。

  2. Empty collection parameter: If the parameter passed in is an empty collection, the method will returnfalse, because no elements were removed.

  3. Null elements:HashSetAllows containingnullelements,removeAll()and can correctly handlenullvalues.

  4. Performance considerations: The time complexity of this method is O(n), where n is the size of the parameter collection. For large collections, this may affect performance.

  5. Modification impact: Calling this method directly modifies the original collection rather than returning a new collection.


Comparison with the retainAll() Method

removeAll()andretainAll()are two opposite operations:

  • removeAll(): Removes elements that are the same as those in the parameter collection (set difference)
  • retainAll(): Retains elements that are the same as those in the parameter collection, removes other elements (set intersection)

Practical Application Scenarios

removeAll()The method is very useful in the following scenarios:

  1. Filtering out unwanted elements
  2. Comparing the differences between two collections
  3. Implementing set subtraction operations
  4. Excluding a specific set of values during data cleaning

Summary

HashSetofremoveAll()The method is a powerful collection operation tool that can efficiently remove elements from a collection in batches. Understanding and correctly using this method can help developers handle collection data more effectively. Remember that it directly modifies the original collection, and use it appropriately according to actual needs.

Java HashSet Java HashSet

Other Extensions