# Replace For-Loop with Stream::Match
# Description
Replaces occurrences of enhanced for-loops which are only used to initialize or return a boolean variable with Stream::anyMatch
, Stream::allMatch
or Stream::noneMatch
.
The stream syntax is more concise and improves readability.
# Benefits
Applying this rule results in better readability.
# Tags
# Code Changes
# Loop with break
statement to Stream::anyMatch
Pre
boolean containsEmpty = false;
for(String value : strings) {
if(value.isEmpty()) {
containsEmpty = true;
break;
}
}
Post
boolean containsEmpty = strings.stream().anyMatch(value -> value.isEmpty());
# Loop with break
statement to Stream::noneMatch
Pre
boolean noneEmpty = true;
for(String value : strings) {
if(value.isEmpty()) {
noneEmpty = false;
break;
}
}
Post
boolean noneEmpty = strings.stream().noneMatch(value -> value.isEmpty());
# Loop with break
statement to Stream::allMatch
Pre
boolean allEmpty = true;
for(String value : strings) {
if(!value.isEmpty()) {
containsEmpty = false;
break;
}
}
Post
boolean allEmpty = strings.stream().allMatch(value -> value.isEmpty());
# Loop with return
statement
Pre
for(String value : strings) {
if(emptyString.equals(value)) {
return true;
}
}
return false
Post
return strings.stream().anyMatch(value -> emptyString.equals(value));
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 | EnhancedForLoopToStreamAnyMatch |
First seen in jSparrow version | 2.2.0 |
Minimum Java version | 8 |
Remediation cost | 2 min |