# Use Stream::map

# Properties

Property Value
Rule ID LambdaForEachMap
First seen in jSparrow version 2.0.0
Minimum Java version 8
Remediation cost 15 min

# Description

Extracts a block from the body of the consumer of the Stream::forEach method and introduces Stream::map instead. This makes complicated code blocks easier to read and reuse.

# Benefits

Arguably the lambda expression is easier to read and can be combined with other stream operations.

# Code Changes

# Unwrapping single statement

Pre

list.stream()
    .filter(s -> !s.isEmpty())
    .forEach(s -> {
        String subString = s.substring(1);
        sb.append(subString);
    });

Post

list.stream()
    .filter(s -> !s.isEmpty())
    .map(s -> s.substring(1))
    .forEach(subString -> sb.append(subString));

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊