Java 8 Stream - forEach() vs forEachOrdered()

By Yashwant Chavan, Views 15562, Date 06-Nov-2016

In this tutorial you will learn about forEach() and forEachOrdered() methods. How it impact while processing stream using parallel() method.

tags java

Refer below steps.

  • 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.
  • In second example, output ("CwhnaasYanva th") is processed in parallel way that's why it affect the order of 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.

Java 8 forEach() Vs forEachOrdered() Example

package com.technicalkeeda.app;

public class Java8ForEach {
    public static void main(String[] args) {

        System.out.println("Using forEach()");
        String str = "Yashwant Chavan";
        str.chars().forEach(n -> System.out.print((char) n));

        System.out.println("\n\nUsing parallel() + forEach()");
        str.chars().parallel().forEach(n -> System.out.print((char) n));

        System.out.println("\n\nUsing parallel() + forEachOrdered()");
        str.chars().parallel().forEachOrdered(n -> System.out.print((char) n));
    }
}

output

Using forEach()
Yashwant Chavan

Using parallel() + forEach()
CwhnaasYanva th

Using parallel() + forEachOrdered()
Yashwant Chavan
Yashwant Chavan

Yashwant Chavan

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan@gmail.com