what is the difference between a stateful and a stateless lambda expression?

前端 未结 5 1114
北荒
北荒 2021-01-12 10:22

According to the OCP book one must avoid stateful operations otherwise known as stateful lambda expression. The definition provided in the book is \'a stateful lambda expres

5条回答
  •  爱一瞬间的悲伤
    2021-01-12 11:04

    Here is an example where a stateful operation returns a different result each time:

    public static void main(String[] args) {
    
    Set seen = new HashSet<>();
    
    IntStream stream = IntStream.of(1, 2, 3, 1, 2, 3);
    
    // Stateful lambda expression
    IntUnaryOperator mapUniqueLambda = (int i) -> {
        if (!seen.contains(i)) {
            seen.add(i);
            return i;
        }
        else {
            return 0;
        }
    };
    
    int sum = stream.parallel().map(mapUniqueLambda).peek(i ->   System.out.println("Stream member: " + i)).sum();
    
    System.out.println("Sum: " + sum);
    }
    

    In my case when I ran the code I got the following output:

    Stream member: 1
    Stream member: 0
    Stream member: 2
    Stream member: 3
    Stream member: 1
    Stream member: 2
    Sum: 9
    

    Why did I get 9 as the sum if I'm inserting into a hashset?
    The answer: Different threads took different parts of the IntStream For example values 1 & 2 managed to end up on different threads.

提交回复
热议问题