Understanding java 8 stream's filter method

前端 未结 2 728
悲&欢浪女
悲&欢浪女 2021-01-13 03:07

I recently learned about Streams in Java 8 and saw this example:

IntStream stream = IntStream.range(1, 20);

Now, let\'s say th

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-13 03:34

    A Stream is a lazy evaluation mechanism for processing Collections efficiently. This means that all the intermediate operations on the Stream are not evaluated unless necessary for the final (terminal) operation.

    In your example, the terminal operation is firstFirst(). This means the Stream will evaluate the pipeline of intermediate operations until it finds a single int that results from passing the input Stream through all the intermediate operations.

    The second filter only receives ints that pass the first filter, so it only processes the numbers 3,6,9,12,15 and then stops, since 15 passes the filter, and supplies the findFirst() operation the only output it needs.

    The first filter will only process ints of the input Stream as long as the terminal operation still requires data, and therefore it will only process 1 to 15.

提交回复
热议问题