Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java For-Each Loop : Sort order [duplicate]

Tags:

java

syntax

loops

Does a java for-each loop guarantee that the elements will be presented in order if invoked on a list? In my tests it does seem to, but I can't seem to find this explicitly mentioned in any documentation

List<Integer> myList;// [1,2,3,4] for (Integer i : myList) {   System.out.println(i.intValue()); }  #output 1,2,3,4 
like image 672
Mike Avatar asked Sep 04 '09 02:09

Mike


People also ask

Does forEach maintain order in Java?

Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.

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.

How does forEach work in Java?

The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.


2 Answers

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".

like image 51
hallidave Avatar answered Sep 28 '22 18:09

hallidave


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>).

like image 38
rjohnston Avatar answered Sep 28 '22 17:09

rjohnston