# 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);
	}

You Want To Have Those Changes Done Automatically?

The automatic application of this rule is supported in the following jSparrow version:

# Properties

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