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

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