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