# Replace For-Loop with Iterable::forEach

# Description

This rule replaces enhanced for loops (for-each-loops) with an invocation of java.lang.Iterable::forEach-method and passes the body of the for-loop as a lambda Consumer parameter.

There are some special cases, in which the transformation won't be possible due to restrictions of lambda expressions and the Consumer interface.

# Benefits

Using functional coding style instead of imperative loops improves the readability and makes the code more compact.

# Tags

# Code Changes

# Single statement in loop body

Pre

for (String string : stringList) {
    System.out.println(string);
}

Post

stringList.forEach(s -> System.out.println(s));

# Multiple statements in loop body

Pre

for (String value : values) {
    int length = value.length();
    if (length > 2) {
        length /= 2;
    }
    print(value.substring(0, length));
}

Post

stringList.forEach(value -> {
    int length = value.length();
    if (length > 2) {
        length /= 2;
    }
    print(value.substring(0, length));
});

🛠️ 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 EnhancedForLoopToStreamForEach
First seen in jSparrow version 2.0.0
Minimum Java version 8
Remediation cost 15 min