With the following code I always get 0 as the first output. Is that guaranteed?
import java.util.Random;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.rope();
}
class Wrapper {
public int x = 0;
}
void rope() {
Stream.generate( Wrapper::new ).limit(100000)
.peek( w -> asum += w.x )
.forEach( w -> mutate( w ) );
System.out.println( asum );
System.out.println( bsum );
}
void mutate( Wrapper w ) {
w.x = r.nextInt(2);
bsum += w.x;
}
protected long asum = 0;
protected long bsum = 0;
Random r = new Random( 0 );
}
According to 'peek' documents "... performing the provided action on each element as elements are consumed ...". However for non-parallel streams it has to be either before or after.
In other words, when the 'terminal operation' happens for an element is it removed from the pipeline before the terminal operation or after?
(I am pretty sure 'before' is the right answer, but trying to understand some complex stream code where the opposite seems to be assumed.)