Java 8 eagerly get the result of an intermediate stream operation -
given following code:
list<string> list = arrays.aslist("a", "b", "c"); list.stream() .map(s -> s + "-" + s) //"a-a", "b-b", "c-c" .filter(s -> !s.equals("b-b")) //"a-a", "c-c" .foreach(s -> system.out.println(s));
map
, filter
intermediate operations , foreach
terminal operation. after execution of terminal operation can have result of data transformation.
is there way force evaluation more eager , have kind of intermediate result - without breaking stream operations chain? example want have list of "a-a", "b-b", "c-c" (which result of first intermediate operation).
you can use peek
:
list<string> allpairs = new arraylist<>(); list<string> list = arrays.aslist("a", "b", "c"); list.stream() .map(s -> s + "-" + s) //"a-a", "b-b", "c-c" .peek(allpairs::add) .filter(s -> !s.equals("b-b")) //"a-a", "c-c" .foreach(s -> system.out.println(s));
this way computation still won't start until terminal operation, can "intercept" stream content @ point , use in way like.
beware if terminal operation short-circuiting (like findfirst
): way not elements might passed peek
.
Comments
Post a Comment