Returns a stream consisting of the elements of this stream that match the given predicate.
This example shows that updating an external variable from behavioral parameter can lead to non-determinist result.
package com.logicbig.example;
import java.util.stream.IntStream;
public class StatefulExample2 {
private static int count = 0;
public static void main (String[] args) {
for (int i = 0; i < 5; i++) {
process();
}
}
private static void process () {
count = 0;
IntStream stream = IntStream.range(1, 1000);
//finding the sum of even numbers
int sum = stream.parallel()
.filter(i -> {
boolean b = i % 2 == 0;
if (b) {
count++;//updating count hence making it stateful.
}
return b;
})
.sum();
System.out.printf("sum :%d count:%d%n", sum, count);
}
}
Output
sum :249500 count:399
sum :249500 count:411
sum :249500 count:456
sum :249500 count:456
sum :249500 count:456
Original PostThis example shows alternative way to do the same thing as above example but in a stateless manner.
package com.logicbig.example;
import java.util.stream.IntStream;
public class StatefulFixExample2 {
public static void main (String[] args) {
for (int i = 0; i < 5; i++) {
process();
}
}
private static void process () {
IntStream stream = IntStream.range(1, 1000);
//finding the even numbers
int[] even = stream.parallel()
.filter(i -> i % 2 == 0)
.toArray();
//finding sum
int sum = IntStream.of(even).parallel().sum();
System.out.printf("sum :%d count:%d%n", sum, even.length);
}
}
Output
sum :249500 count:499
sum :249500 count:499
sum :249500 count:499
sum :249500 count:499
sum :249500 count:499
Original Post