# Replace Set.removeAll With ForEach

# Description

Calling the method java.util.Set#removeAll(java.util.Collection) (opens new window) with an instance of java.util.List (opens new window) as an argument may lead to performance problems due to a possible O(n^2) complexity. This rule replaces such invocations. For example, the invocation mySet.removeAll(myList); is replaced by myList.forEach(mySet::remove);.

# Benefits

The benefit of applying this rule may depend on your installed Java version and on the subtype of the Set on which the 'removeAll' method is invoked. Benchmark tests on our systems indicated an improvement. However, we recommend you to carry out all necessary performance tests before applying this rule.

# Tags

# Code Changes

# Remove all elements of an ArrayList from a HashSet


	void removeStringsFromSet(Set<String> stringSet, List<String> stringList) {


	void removeStringsFromSet(Set<String> stringSet, List<String> stringList) {

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID ReplaceSetRemoveAllWithForEach
First seen in jSparrow version 4.13.0
Minimum Java version 8
Remediation cost 5 min