Replace For-Loop with Stream::Match

Properties

Property Value
First seen in jSparrow version 2.2.0
Updated in jSparrow version 3.3.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.

Requirement & Tags

Requirements

Java 8

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