forEach() vs. forEachOrdered() in Java Stream

When working with Java Streams, you often encounter situations where you need to apply a function to each element of a stream. Two common methods for this task are forEach() and forEachOrdered(). In this blog, we will explore the differences between these methods and provide guidance on when to use each one.

1. forEach()

The forEach() method is a fundamental operation in Java Streams, and it’s used to apply a specified action to each element of a stream. Here’s a basic example:

List<String> names = Arrays.asList("Sagar", "Priyanka", "Pradnya", "Manish"); -> System.out.println(name));

The code above will print the names in an order that is dependent on the underlying stream implementation. This means the order might not be the same as the order in the original list.

2. forEachOrdered()

In contrast, the forEachOrdered() method ensures that elements are processed in the same order as they appear in the source stream. This guarantees that the order is preserved. Let’s look at the same example with forEachOrdered():

List<String> names = Arrays.asList("Sagar", "Priyanka", "Pradnya", "Manish"); -> System.out.println(name));

In this case, the names will be printed in the exact order they appear in the list, regardless of the underlying stream implementation.

3. Choosing the Right Method

Now that we understand the difference, how do we decide which method to use? The choice between forEach() and forEachOrdered() depends on the specific requirements of your task.

  • Use forEach() when order doesn’t matter: If the order of processing doesn’t affect the correctness or outcome of your operation, forEach() is more efficient, especially for parallel streams. It can provide better performance in cases where the order doesn’t need to be preserved.
  • Use forEachOrdered() when order is crucial: If maintaining the original order of elements is vital to your task, such as when dealing with time-series data or a sequence that must be processed in order, then forEachOrdered() is the appropriate choice. It ensures that elements are processed in the order they appear in the stream.

4. References

  1. Java 8 Stream generate() Method
  2. Java 8 Stream filter() Method Example
  3. Java Stream map() vs flatMap() Method
  4. Java 8 Stream API – JavaDoc

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.