Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java's foreach loop preserve order?

Tags:

java

foreach

Does Java's foreach loop start at the first object and in a linear fashion work it's way to the end? For example

String[] names = new String[] {"Zoe", "Bob", "Charlie", "Alex"}; for(String name : names) {   //do stuff... } 

Is the string "Zoe" always processed first, followed by "Bob" etc? No sorting happens? I've tested it out myself and haven't found any but I need a guarantee and couldn't find anything in the docs.

like image 480
Celeritas Avatar asked Jan 26 '16 09:01

Celeritas


People also ask

Does forEach guarantee order Java?

The behavior of forEach() operation is explicitly non-deterministic. For parallel streams, forEach() operation does not guarantee to respect the encounter order of the Stream.

Does enhanced for loop go in order?

3) The enhanced for loop can only iterate in incremental order. we cannot configure it to go in decrement.

Does iterator maintain order?

Iteration OrderThe order in which the elements contained in a Java Iterator are traversed depends on the object that supplies the Iterator . For instance, an iterator obtained from a List will iterate through the elements of that List in the same order the elements are stored internally in the List .

Does forEach preserve order C#?

Yes. An (IList) is ordered, and iterating will iterate from the first item to the last, in order inserted (assuming you always inserted at the end of the list as opposed to somewhere else, depending on the methods you used).


1 Answers

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)

like image 108
Simulant Avatar answered Oct 05 '22 21:10

Simulant