Java Stream Using Previous Element in Foreach Lambda -


i have list of numbers 0s inside. since 0 means invalid measure in situation, need change 0 valued element first non 0 element can find in previous positions.

for example list

45 55 0 0 46 0 39 0 0 0 

must become

45 55 55 55 46 46 39 39 39 39 

this implementation using classic for each

      int lastnonzeroval = 0;         (mntrroastdvo vo : res) {             if (vo.getvalcolor() > 0) {                 lastnonzeroval = vo.getvalcolor();             } else {                 vo.setvalcolor(lastnonzeroval);             }         } 

is there way implement java streams , lambda functions?

since know must not change source of stream in foreach lambda, list list of object , not change element of list assign new values.

this first solution

int lastnonzeroval = 1; resutl.stream().foreach(vo -> {         if(vo.getvalcolor()>0){             lastnonzeroval=vo.getvalcolor();         }else{             vo.setvalcolor(lastnonzeroval);         } }); 

but read here

it's best if lambdas passed stream operations entirely side effect free. is, don't mutate heapbased state or perform i/o during execution.

this worryng me

the data partitioned, there's no guarantee when given element processed, elements preceding element processed.

can solution produce invalid results, maybe when number of elements in list high? ? event if not use parallelstream() ?

you can modify state of objects inside stream. can not modify data source state.

the problem same in classic iterating.

use foreachordered() perform

an action each element of stream, in encounter order of stream if stream has defined encounter order

if call

result.stream.foreachordered(...) 

all elements processed sequentially in order.

for sequential streams foreach seems respect order.


Comments