I have a list of numbers with some 0s inside. Since 0 means invalid measure in my situation, I need change the 0 valued element with the first non 0 element that I can find in the previous positions.
For example the list
45 55 0 0 46 0 39 0 0 0
must become
45 55 55 55 46 46 39 39 39 39
This is the implementation using the classic for each
int lastNonZeroVal = 0;
for (MntrRoastDVO vo : res) {
if (vo.getValColor() > 0) {
lastNonZeroVal = vo.getValColor();
} else {
vo.setValColor(lastNonZeroVal);
}
}
Is there a way to implement this with the Java Streams and Lambda Functions?
Since I know that I must not change the source of the stream in the foreach lambda, actually the list is a list of object and I do not change the element of the list but I just assign new values.
This was my first solution
int lastNonZeroVal = 1;
resutl.stream().forEach(vo -> {
if(vo.getValColor()>0){
lastNonZeroVal=vo.getValColor();
}else{
vo.setValColor(lastNonZeroVal);
}
});
But I also read here
It's best if the lambdas passed to stream operations are entirely side effect free. that is, that they don't mutate any heapbased state or perform any I/O during their execution.
This is what is worryng me
the data is partitioned, there's no guarantee that when a given element is processed, all elements preceding that element were already processed.
Can this solution produce invalid results, maybe when the number of elements in the list are high? ?
Event if I do not use parallelStream() ?