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

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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