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 OverflowYes. 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)
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
forloop 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 }#aand#iare 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 correspondingIterator(retrieved by callingIterable.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 }#iis 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).
Yes. The foreach loop will iterate through the list in the order provided by the iterator() method. See the documentation for the Iterable interface.
If you look at the Javadoc for List you can see that a list is an "ordered collection" and that the iterator() method returns an iterator that iterates "in proper sequence".
The foreach loop will use the iterator built into the Collection, so the order you get results in will depend whether or not the Collection maintains some kind of order to the elements.
So, if you're looping over an ArrayList, you'll get items in the order they were inserted (assuming you didn't go on to sort the ArrayList). If you're looping over a HashSet, all bets are off, since HashSets don't maintain any ordering.
If you need to guarantee an order to the elements in the Collection, define a Comparator that establishes that order and use Collections.sort(Collection<T>, Comparator<? super T>).
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.
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.