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.
This may be an option. Hope there is a better way to start from last element than to while loop to the end.
Not without writing some custom code which will give you an enumerator which will reverse the elements for you.
You should be able to do it in Java by creating a custom implementation of Iterable which will return the elements in reverse order.
Then, you would instantiate the wrapper (or call the method, what-have-you) which would return the Iterable implementation which reverses the element in the for each loop.
As of the comment: You should be able to use Apache Commons
ReverseListIterator
As @rogerdpack said, you need to wrap the
ReverseListIterator
as anIterable
.A work Around :
Or with guava :
AFAIK there isn't a standard "reverse_iterator" sort of thing in the standard library that supports the for-each syntax which is already a syntactic sugar they brought late into the language.
You could do something like for(Item element: myList.clone().reverse()) and pay the associated price.
This also seems fairly consistent with the apparent phenomenon of not giving you convenient ways to do expensive operations - since a list, by definition, could have O(N) random access complexity (you could implement the interface with a single-link), reverse iteration could end up being O(N^2). Of course, if you have an ArrayList, you don't pay that price.
The Collections.reverse method actually returns a new list with the elements of the original list copied into it in reverse order, so this has O(n) performance with regards to the size of the original list.
As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order.
For example:
And you would use it like: