Yes. The order is not changed. This applies to all types of collections of the Java Collection Framework implementing the iterator interface that is used by the for-loop. If you want to sort your Array, you can use Arrays.sort(names)

Answer from Simulant on Stack Overflow
Top answer
1 of 2
74

Yes. The order is not changed. This applies to all types of collections of the Java Collection Framework implementing the iterator interface that is used by the for-loop. If you want to sort your Array, you can use Arrays.sort(names)

2 of 2
53

The enhanced for loop is specified in JLS 14.14.2, where its equivalent code is written.

It can be used to loop over arrays and instances of Iterable.

  • For an array, the order of iteration will be always preserved and be consistent between runs. This is because it is equivalent to a simple for loop with an index going from the beginning of the array to its end.

    The enhanced for statement is equivalent to a basic for statement of the form:

    T[] #a = Expression;
    L1: L2: ... Lm:
    for (int #i = 0; #i < #a.length; #i++) {
        {VariableModifier} TargetType Identifier = #a[#i];
        Statement
    }
    

    #a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

  • For an Iterable, it will follow the order of the corresponding Iterator (retrieved by calling Iterable.iterator()), that may or may not be consistent between runs.

    The enhanced for statement is equivalent to a basic for statement of the form:

    for (I #i = Expression.iterator(); #i.hasNext(); ) {
    {VariableModifier} TargetType Identifier =
        (TargetType) #i.next();
        Statement
    }
    

    #i is an automatically generated identifier that is distinct from any other identifiers (automatically generated or otherwise) that are in scope (§6.3) at the point where the enhanced for statement occurs.

    You should refer to the Javadoc of each type to see if an order is consistent or not. For example, it is explicitely specified that for List, the iterator retains the order:

    Returns an iterator over the elements in this list in proper sequence.

    While it is explicitely specified that for Set, the order is unspecified (unless an extra guarantee is made):

    The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).

🌐
Codecademy
codecademy.com › docs › java › arraylist › .foreach()
Java | ArrayList | .forEach() | Codecademy
April 13, 2025 - Yes, for ArrayList, the `.forEach()` method processes elements in the same order they appear in the list, from index 0 to the last index. 5. Can `.forEach()` be used with null elements in the ArrayList?
🌐
Medium
medium.com › @AlexanderObregon › javas-stream-foreachordered-explained-170e6a75c235
Java’s Stream.forEachOrdered() Explained | Medium
September 17, 2024 - The elements are processed in the exact order they appear in the list because a sequential stream maintains that order by default. However, things start to change when parallel streams come into play.
🌐
Educative
educative.io › answers › what-is-the-foreachordered-method-of-the-stream-interface
What is the forEachOrdered() method of the Stream Interface?
Aggregate operations iterate over and process these substreams in parallel, and then combine the results. When we use forEachOrdered, the elements are looped in the encounter order if the stream has a defined encounter order.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream foreachordered()
Java Stream forEachOrdered() with Examples - HowToDoInJava
March 15, 2022 - List<Integer> list = Arrays.asList(2, 4, 6, 8, 10); list.stream() .sorted(Comparator.reverseOrder()) .forEachOrdered(System.out::println); Program output. ... Drop me your questions related to the Stream forEachOrdered() method in Java Stream API.
🌐
Tech with Maddy
techwithmaddy.com › how-does-the-foreach-loop-work-in-java
How does the "forEach" loop work in Java?
October 24, 2021 - Looping through the filtered list and printing the items using a lambda expression. If you want to ensure that the items are printed in order, you can use the forEachOrdered() method. This method is a terminal operator.
🌐
Baeldung
baeldung.com › home › java › java collections › the difference between collection.stream().foreach() and collection.foreach()
The Difference Between stream().forEach() and forEach() | Baeldung
September 17, 2025 - If we want to use functional-style Java, we can also use forEach(). ... In this simple case, it doesn’t make a difference which forEach() we use. Collection.forEach() uses the collection’s iterator (if one is specified), so the processing order of the items is defined.
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-foreach-method-in-java
ArrayList forEach() Method in Java - GeeksforGeeks
July 11, 2025 - Example 3: Here, we will use the forEach() method with a conditional statement to filter and print eligible elements of an ArrayList of Integers. ... // Java program to demonstrate // conditional actions using forEach() import java.util.ArrayList; public class GFG { public static void main(String[] args) { // Create an ArrayList of Integers ArrayList<Integer> a = new ArrayList<>(); a.add(24); a.add(18); a.add(10); // Use forEach() to print // ages that are 18 or above a.forEach(age -> { if (age >= 18) { System.out.println("Eligible age: " + age); } }); } }
Find elsewhere
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-foreach
Java 8 forEach method with example
However when working with parallel streams, you would always want to use the forEachOrdered() method when the order matters to you, as this method guarantees that the order of elements would be same as the source. Lets take an example to understand the difference between forEach() and forEachOrdered(). import java.util.List; import java.util.ArrayList; public class Example { public static void main(String[] args) { List<String> names = new ArrayList<String>(); names.add("Maggie"); names.add("Michonne"); names.add("Rick"); names.add("Merle"); names.add("Governor"); //forEach - the output would
🌐
Baeldung
baeldung.com › home › java › java list › ways to iterate over a list in java
Ways to Iterate Over a List in Java | Baeldung
June 27, 2025 - A ListIterator allows us to traverse a list of elements in either forward or backward order.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › foreach.html
The For-Each Loop
2 weeks ago - List suits = ...; List ranks = ...; List sortedDeck = new ArrayList(); // BROKEN - throws NoSuchElementException!
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › java arraylist foreach()
Java ArrayList forEach() with Examples - HowToDoInJava
January 12, 2023 - The ArrayList forEach() method performs the specified Consumer action on each element of the List until all elements have been processed or the action throws an exception. By default, actions are performed on elements taken in the order of iteration.
🌐
ConcretePage
concretepage.com › java › java-8 › java-stream-foreachordered-vs-foreach
Java Stream : forEachOrdered() vs forEach()
The forEachOrdered method always guarantee the encounter order. Stream.of("A","B","C", "D") .parallel() .forEachOrdered(e -> System.out.println(e)); The output is A B C D. Java doc: Stream · <- Java Lambda Expressions · Convert Java Stream ...
🌐
W3Schools
w3schools.com › java › ref_arraylist_foreach.asp
Java ArrayList forEach() Method
Java Examples Java Videos Java ... Java Certificate · ❮ ArrayList Methods · Use a lambda expression in the ArrayList's forEach() method to print every item in the list: import java.util.ArrayList; public class Main { ...
Top answer
1 of 4
119
Stream.of("AAA","BBB","CCC").parallel().forEach(s->System.out.println("Output:"+s));
Stream.of("AAA","BBB","CCC").parallel().forEachOrdered(s->System.out.println("Output:"+s));

The second line will always output

Output:AAA
Output:BBB
Output:CCC

whereas the first one is not guaranted since the order is not kept. forEachOrdered will processes the elements of the stream in the order specified by its source, regardless of whether the stream is sequential or parallel.

Quoting from forEach Javadoc:

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

When the forEachOrdered Javadoc states (emphasis mine):

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

2 of 4
41

Although forEach shorter and looks prettier, I'd suggest to use forEachOrdered in every place where order matters to explicitly specify this. For sequential streams the forEach seems to respect the order and even stream API internal code uses forEach (for stream which is known to be sequential) where it's semantically necessary to use forEachOrdered! Nevertheless you may later decide to change your stream to parallel and your code will be broken. Also when you use forEachOrdered the reader of your code sees the message: "the order matters here". Thus it documents your code better.

Note also that for parallel streams the forEach not only executed in non-determenistic order, but you can also have it executed simultaneously in different threads for different elements (which is not possible with forEachOrdered).

Finally both forEach/forEachOrdered are rarely useful. In most of the cases you actually need to produce some result, not just side-effect, thus operations like reduce or collect should be more suitable. Expressing reducing-by-nature operation via forEach is usually considered as a bad style.

🌐
W3Resource
w3resource.com › java-tutorial › arraylist › arraylist_foreach.php
Java ArrayList.forEach Method - w3resource
August 19, 2022 - Java ArrayList.forEach() Method: ... otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified)....
🌐
Medium
neesri.medium.com › master-in-java-8-foreach-48ac3fc940dc
Master in the forEach() Method in Java 8 | by A cup of JAVA coffee with NeeSri | Medium
August 3, 2024 - List<String> list = Arrays.asList("apple", "banana", "orange"); // Java 8 forEach on Stream list.stream().forEach(item -> System.out.println(item)); // Java 7 loop on Stream for (String item : list) { System.out.println(item); } list.forEach(item -> { if (item != null) { // Perform some action } }); list.forEach(item -> { try { // Perform some operation that may throw an exception } catch (Exception e) { // Handle the exception } }); list.stream().forEach(item -> System.out.println(item)); // May not maintain order list.stream().forEachOrdered(item -> System.out.println(item)); // Maintains order
🌐
Crunchify
crunchify.com › java j2ee tutorials › how to iterate through java list? seven (7) ways to iterate through loop in java
How to iterate through Java List? Seven (7) ways to Iterate Through Loop in Java • Crunchify
December 28, 2025 - This tutorial demonstrates the use of ArrayList, Iterator and a List. ... You need JDK 13 to run below program as point-5 above uses stream() util. void java.util.stream.Stream.forEach(Consumer<? super String> action) performs an action for each element of this stream.