Iterating through a list in reverse order in java
Guava offers Lists#reverse(List)
and ImmutableList#reverse()
. As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList
, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.
Example
List reversed = ImmutableList.copyOf(myList).reverse();
Try this:
// Substitute appropriate type.
ArrayList<...> a = new ArrayList<...>();
// Add elements to list.
// Generate an iterator. Start just after the last element.
ListIterator li = a.listIterator(a.size());
// Iterate in reverse.
while(li.hasPrevious()) {
System.out.println(li.previous());
}