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

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