Java 8 stream operations execution order

后端 未结 5 1549
隐瞒了意图╮
隐瞒了意图╮ 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:22

    The behavior you noticed is the correct one. In order to find out if a number passes the entire Stream pipeline, you have to run that number through all the pipeline steps.

    filtering 1 // 1 doesn't pass the filter
    filtering 2 // 2 passes the filter, moves on to map
    mapping 2 // 2 passes the map and limit steps and is added to output list
    filtering 3 // 3 doesn't pass the filter
    filtering 4 // 4 passes the filter, moves on to map 
    mapping 4 // 4 passes the map and limit steps and is added to output list
    

    now the pipeline can end, since we have two numbers that passed the pipeline.

提交回复
热议问题