title: Java Stream Using Previous Element in Foreach Lambda
body: <p>I have a list of numbers with some <code>0s</code> inside. Since <code>0</code> means invalid measure in my situation, I need change the <code>0</code> valued element  with the first non 0 element that I can find in the previous positions.</p>
  
  <p>For example the list </p>
  
  <pre><code>45 55 0 0 46 0 39 0 0 0
  </code></pre>
  
  <p>must become</p>
  
  <pre><code>45 55 55 55 46 46 39 39 39 39
  </code></pre>
  
  <p>This is the implementation using the classic <code>for each</code></p>
  
  <pre><code>      int lastNonZeroVal = 0;
          for (MntrRoastDVO vo : res) {
              if (vo.getValColor() &gt; 0) {
                  lastNonZeroVal = vo.getValColor();
              } else {
                  vo.setValColor(lastNonZeroVal);
              }
          }
  </code></pre>
  
  <p>Is there a way to implement this with the Java Streams and Lambda Functions?</p>
  
  <p>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.</p>
  
  <p>This was my first solution</p>
  
  <pre><code>int lastNonZeroVal = 1;
  resutl.stream().forEach(vo -&gt; {
          if(vo.getValColor()&gt;0){
              lastNonZeroVal=vo.getValColor();
          }else{
              vo.setValColor(lastNonZeroVal);
          }
  });
  </code></pre>
  
  <p>But I also read <a href="http://www.ibm.com/developerworks/library/j-java-streams-1-brian-goetz/index.html" rel="noreferrer">here</a></p>
  
  <blockquote>
    <p>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.</p>
  </blockquote>
  
  <p>This is what is worryng me</p>
  
  <blockquote>
    <p>the data is partitioned, there's no guarantee that when a given element  is 
    processed, all elements preceding that element were already processed.</p>
  </blockquote>
  
  <p>Can this solution  produce invalid results, maybe when the number of elements in the list are high? ?
  Event if I do not use <code>parallelStream()</code> ?</p>