# Replace For-Loop with Stream::Match
# Properties
Property | Value |
---|---|
Rule ID | EnhancedForLoopToStreamAnyMatch |
First seen in jSparrow version | 2.2.0 |
Minimum Java version | 8 |
Remediation cost | 2 min |
# 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.
# 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));
Automatic Application of This Rule
The automatic application of this rule is supported in the following jSparrow version:
# Tags
← Replace For-Loop with Enhanced-For-Loop Replace For-Loop with Stream::collect(Collectors.joining()) →
1
You & jSparrow