Stream ForEachOrdered

In a Sequential Stream, the forEach will process the elements in the same order as in the Source Stream, but in Parallel Streams where multiple threads will be processing the elements, the order is not guaranteed hence forEach will print elements in a different order each time. The forEachOrdered makes sure the elements are in the correct order as per the source stream.

package org.wesome.java8;

import java.util.stream.IntStream;

class Apple {
    public static void main(String args[]) {
        System.out.println("*---------------------------for Each---------------------------*");
        IntStream.rangeClosed(1, 10).parallel().forEach(value -> System.out.println("for each- " + value));

        System.out.println("*---------------------------for Each Ordered---------------------------*");
        IntStream.rangeClosed(1, 10).parallel().forEachOrdered(value -> System.out.println("ordered- " + value));
    }
}

 

follow us on