# Use Stream::collect

# Properties

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

# Description

Replaces Stream::forEach with Stream::collect if the argument of the forEach statement is only used for adding elements to a list. This simplifies adding elements to a list.

# Benefits

This rule provides an easier-to read alternative to add items in a list.

# Code Changes

Pre

objectList.stream()
    .map(o -> o.substring(0))
    .forEach( oString -> {
         oStrings.add(oString);
     });

Post

oStrings.addAll(objectList.stream()
    .map(o -> o.substring(0))
    .collect(Collectors.toList()));

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? 😊