# 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

Pre

	void removeStringsFromSet(Set<String> stringSet, List<String> stringList) {
		stringSet.removeAll(stringList);
	}

Post

	void removeStringsFromSet(Set<String> stringSet, List<String> stringList) {
		stringList.forEach(stringSet::remove);
	}

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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