Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 299
alexgbelov Avatar asked May 05 '17 23:05

alexgbelov


People also ask

What would you use while processing a stream to replace every element in a stream with a different value?

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.

Can we use forEach in streams Java?

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.

How do you loop through each element in a stream?

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.

What is the purpose of limit method of stream in Java 8?

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.


2 Answers

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.

like image 107
Bohemian Avatar answered Oct 05 '22 15:10

Bohemian


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

example:

List<String> strings = stream .map(Object::toString) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); 
like image 38
csenga Avatar answered Oct 05 '22 17:10

csenga