Java 8 apply function to all elements of Stream without breaking stream chain

There are (at least) 3 ways. For the sake of example code, I've assumed you want to call 2 consumer methods methodA and methodB:

A. Use peek():

list.stream().peek(x -> methodA(x)).forEach(x -> methodB(x));

Although the docs say only use it for "debug", it works (and it's in production right now)

B. Use map() to call methodA, then return the element back to the stream:

list.stream().map(x -> {method1(x); return x;}).forEach(x -> methodB(x));

This is probably the most "acceptable" approach.

C. Do two things in the forEach():

list.stream().forEach(x -> {method1(x); methodB(x);});

This is the least flexible and may not suit your need.


You are looking for the Stream's map() function.

example:

List<String> strings = stream
.map(Object::toString)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);