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

chaining, java, java-8, java-stream

Solution

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.

Problem

Is there a way in Java to apply a function to all the elements of a `Stream` without breaking the `Stream` chain? I know I can call `forEach`, but that method returns a `void`, not a `Stream`.

Original source