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
forEachOrdered(). In this blog, we will explore the differences between these methods and provide guidance on when to use each one.
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"); names.stream().forEach(name -> 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.
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
List<String> names = Arrays.asList("Sagar", "Priyanka", "Pradnya", "Manish"); names.stream().forEachOrdered(name -> 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
forEachOrdered() depends on the specific requirements of your task.
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.
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.
- Java 8 Stream generate() Method
- Java 8 Stream filter() Method Example
- Java Stream map() vs flatMap() Method
- Java 8 Stream API – JavaDoc
- Java – Capitalize the first letter of a String
- Java 8 Default and Static Methods in Interfaces
- How to iterate Enum in Java
- ConcurrentModificationException in Java
- Core Java Interview Questions and Answers Part 5