Java 8 stream operations execution order

后端 未结 5 1544
隐瞒了意图╮
隐瞒了意图╮ 2020-12-28 18:35
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
List twoEvenSquares = numbers.stream().filter(n -> {
    System.out.println(\"         


        
5条回答
  •  时光取名叫无心
    2020-12-28 19:32

    The Stream API is not meant to provide guarantees regarding order of the execution of the operations. That’s why you should use side-effect free functions. The “short circuiting” does not change anything about it, it’s only about not performing more operations than necessary (and completing in finite time when possible, even for infinite stream sources). And when you look at your output you’ll find that everything works right. The performed operations match the ones you expected and so does the result.

    Only the order doesn’t match and that’s not because of the concept but your wrong assumption about the implementation. But if you think about how an implementation which does not use an intermediate storage has to look like, you will come to the conclusion that it has to be exactly like observed. A Stream will process each item one after another, filtering, mapping and collecting it before the next one.

提交回复
热议问题