forEach vs forEachOrdered in Java 8 Stream

前端 未结 3 2067
感动是毒
感动是毒 2020-11-27 11:35

I understand that these methods differ the order of execution but in all my test I cannot achieve different order execution.

Example:

System.out.prin         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 12:16

    Stream.of("AAA","BBB","CCC").parallel().forEach(s->System.out.println("Output:"+s));
    Stream.of("AAA","BBB","CCC").parallel().forEachOrdered(s->System.out.println("Output:"+s));
    

    The second line will always output

    Output:AAA
    Output:BBB
    Output:CCC
    

    whereas the first one is not guaranted since the order is not kept. forEachOrdered will processes the elements of the stream in the order specified by its source, regardless of whether the stream is sequential or parallel.

    Quoting from forEach Javadoc:

    The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

    When the forEachOrdered Javadoc states (emphasis mine):

    Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

提交回复
热议问题