forEach vs forEachOrdered in Java 8 Stream

前端 未结 3 2060
感动是毒
感动是毒 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

    forEach() method performs an action for each element of this stream. For parallel stream, this operation does not guarantee to maintain order of the stream.

    forEachOrdered() method performs an action for each element of this stream, guaranteeing that each element is processed in encounter order for streams that have a defined encounter order.

    take the example below:

        String str = "sushil mittal";
        System.out.println("****forEach without using parallel****");
        str.chars().forEach(s -> System.out.print((char) s));
        System.out.println("\n****forEach with using parallel****");
    
        str.chars().parallel().forEach(s -> System.out.print((char) s));
        System.out.println("\n****forEachOrdered with using parallel****");
    
        str.chars().parallel().forEachOrdered(s -> System.out.print((char) s));
    

    Output:

    ****forEach without using parallel****
    
    sushil mittal
    
    ****forEach with using parallel****
    
    mihul issltat
    
    ****forEachOrdered with using parallel****
    
    sushil mittal
    

提交回复
热议问题