# Replace For-Loop with Stream::findFirst

# Description

Replaces enhanced for-loops which are used to find an element within a collection by a stream and uses Stream::findFirst to find the result. By using the stream syntax, a multi-line control statement can be reduced to a single line.

# Benefits

Applying this rule results in better readability.

# Tags

# Code Changes

# Loop with break statement

Pre

String key = "";
List<String> values = generateList(input);
for(String value : values) {
    if(value.length() > 4) {
         key = value;
         break;
    }
}

Post

List<String> values = generateList(input);
String key = values.stream()
    .filter(value -> value.length() > 4)
    .findFirst()
    .orElse("");

# Loop with return statement

Pre

for(String value : values) {
    if(value.length() > 4) {
        return value;
    }
}  
return "";

Post

return values.stream()
    .filter(value -> value.length() > 4)
    .findFirst()
    .orElse("");

# Implicit casting

Pre

double defaultValue = -1.0;
double defaultIndex = defaultValue;
List<Integer> values = new ArrayList<>();
for(int value : values) {
    if(value > 4) {
        defaultIndex = value;
        break;
    }
}

Post

double defaultValue = -1.0;
List<Integer> values = new ArrayList<>();
double defaultIndex = values.stream()
    .filter(value -> value > 4)
    .findFirst()
    .map(Double::valueOf)
    .orElse(defaultValue);

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.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID EnhancedForLoopToStreamFindFirst
First seen in jSparrow version 2.2.0
Minimum Java version 8
Remediation cost 2 min