What's the better way to add elements from a Stream to an existing List?
<p>I have to write some code that adds the content of a Java 8 Stream to a List multiple times, and I'm having trouble figuring out what's the best way to do it. Based on what I read on SO (mainly this question: <a href="https://stackoverflow.com/q/22753755">How to add elements of a Java8 stream into an existing List</a>) and elsewhere, I've narrowed it down to the following options:</p>

<pre><code>import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Accumulator&lt;S, T&gt; {


    private final Function&lt;S, T&gt; transformation;
    private final List&lt;T&gt; internalList = new ArrayList&lt;T&gt;();

    public Accumulator(Function&lt;S, T&gt; transformation) {
        this.transformation = transformation;
    }

    public void option1(List&lt;S&gt; newBatch) {
        internalList.addAll(newBatch.stream().map(transformation).collect(Collectors.toList()));
    }

    public void option2(List&lt;S&gt; newBatch) {
        newBatch.stream().map(transformation).forEach(internalList::add);
    }
}
</code></pre>

<p>The idea is that the methods would be called multiple times for the same instance of <code>Accumulator</code>. The choice is between using an intermediate list and calling<code>Collection.addAll()</code> once outside of the stream or calling <code>collection.add()</code> from the stream for each element.</p>

<p>I would tend to prefer option 2 which is more in the spirit of functional programming, and avoid creating an intermediate list, however, there might be benefits to calling <code>addAll()</code> instead of calling <code>add()</code> n times when n is large.</p>

<p>Is one of the two options significantly better than the other ?</p>

<p>EDIT: JB Nizet has a very cool <a href="https://stackoverflow.com/a/39495513/425682">answer</a> that delays the transformation until all batches have been added. In my case, it is required that the transformation is performed straight-away.</p>

<p><em>PS: In my example code, I've used <code>transformation</code> as a placeholder for whatever operations which need to be performed on the stream</em></p>