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

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -