# 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
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);
}
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.
# Properties
Property | Value |
---|---|
Rule ID | ReplaceSetRemoveAllWithForEach |
First seen in jSparrow version | 4.13.0 |
Minimum Java version | 8 |
Remediation cost | 5 min |