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

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