Use Stream::collect

Properties

Property Value
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.

Requirement & Tags

Requirements

Java 8

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