# 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));
🛠️ Auto-refactor Available
You can auto refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.
# Properties
Property | Value |
---|---|
Rule ID | EnhancedForLoopToStreamAnyMatch |
First seen in jSparrow version | 2.2.0 |
Minimum Java version | 8 |
Remediation cost | 2 min |