Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #257 Traverse list backwards

Print each index i and value x from the list items, from the last down to the first.

for(int i = items.length-1;i>=0;i--){
	System.out.println("Index:"+ i +", Value:" + items[i]); 
}
import static java.lang.System.out;
import static java.util.stream.IntStream.iterate;
int n = items.size();
iterate(n - 1, x -> x - 1)
    .limit(n)
    .forEach(i -> {
        out.println(i + " " + items.get(i));
    });
import static java.lang.System.out;
T x;
int i = items.size() - 1;
while (i != -1) {
    x = items.get(i);
    out.printf("%s %s%n", i--, x);
}
import static java.lang.System.out;
import static java.util.Collections.reverse;
reverse(items);
int i = items.size() - 1;
for (T x : items)
    out.printf("%s %s%n", i--, x);
import static java.lang.System.out;
import java.util.ListIterator;
ListIterator<X> g
    = items.reversed().listIterator();
X x;
int i, n = items.size() - 1;
while (g.hasNext()) {
    i = g.nextIndex();
    x = g.next();
    out.printf("%s %s%n", n - i, x);
}

The `next` method will advance the iterator.
for(int i = items.Count - 1; i >= 0; i--)
{
    Console.WriteLine($"Index = {i}, Item = {items[i]}");
}

New implementation...
< >
programming-idioms.org