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
.
In a nutshell, flatMap lets you replace each value of a stream with another stream, and then it concatenates all the generated streams into one single stream.
Stream forEach() method in Java with examplesStream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Java Stream forEach() method is used to iterate over all the elements of the given Stream and to perform an Consumer action on each element of the Stream.
The limit method of the Stream class introduced in Java 8 allows the developer to limit the number of elements that will be extracted from a stream. The limit method is useful in those applications where the user wishes to process only the initial elements that occur in the stream.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With