I need to run through a List in reverse order using Java.
So where this does it forwards:
for(String string: stringList){
//...do something
}
Is there some way to iterate the stringList in reverse order using the for each syntax?
For clarity: I know how to iterate a list in reverse order but would like to know (for curiosity's sake ) how to do it in the for each style.
You can use the Collections class http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html to reverse the list then loop.
All answers above only fulfill the requirement, either by wrapping another method or calling some foreign code outside;
Here is the solution copied from the Thinking in Java 4th edition, chapter 11.13.1 AdapterMethodIdiom;
Here is the code:
Definitely a late answer to this question. One possibility is to use the ListIterator in a for loop. It's not as clean as colon-syntax, but it works.
Credit for the ListIterator syntax goes to "Ways to iterate over a list in Java"
You'd need to reverse your collection if you want to use the for each syntax out of the box and go in reverse order.
This will mess with the original list and also needs to be called outside of the loop. Also you don't want to perform a reverse every time you loop - would that be true if one of the
Iterables.reverse ideas
was applied?The List (unlike the Set) is an ordered collection and iterating over it does preserve the order by contract. I would have expected a Stack to iterate in the reverse order but unfortunately it doesn't. So the simplest solution I can think of is this:
I realize that this is not a "for each" loop solution. I'd rather use the for loop than introducing a new library like the Google Collections.
Collections.reverse() also does the job but it updates the list as opposed to returning a copy in reverse order.