This intermediate operation, returns a stream consisting of the results of applying the given mapper function to the elements of this stream.
This example shows that accessing external state from map method, can lead to non-determinist result.
package com.logicbig.example;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;
public class StatefulExample {
public static void main (String[] args) {
for (int i = 0; i < 10; i++) {
Set<Integer> seen = new HashSet<>();
IntStream stream = IntStream.of(1, 2, 1, 2, 3, 4, 4, 5);
int sum = stream.parallel().map(
//stateful behavioral parameter.
e -> {
try {//making it bit slow for more thread
//interference changes
Thread.sleep(10);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (seen.add(e))
return e;
else
return 0;
}).sum();
System.out.println(sum);
}
}
}
Output
15
15
15
17
17
20
15
15
16
16
Original PostThis example shows alternative way to do the same thing so avoiding statefulness from an intermediate function.
package com.logicbig.example;
import java.util.stream.IntStream;
public class StatefulFixExample {
public static void main (String[] args) {
for (int i = 0; i < 10; i++) {
IntStream stream = IntStream.of(1, 2, 1, 2, 3, 4, 4, 5);
int sum = stream.parallel().distinct().sum();
System.out.println(sum);
}
}
}
Output
15
15
15
15
15
15
15
15
15
15
Original Post