# Use Stream::collect

# 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.

# Tags

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

You Want To Have Those Changes Done Automatically?

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

# Properties

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