Home > coding, java > Iterate in reverse order over a list in Java

Iterate in reverse order over a list in Java

Sometimes we want to iterate in reverse order over a list in Java – without (re)sorting the list. Code example:

    for (T item : backwards(list)) {
        // do something
    }

Here is a backwards() method that does this for you (maybe put this code into a util class and use a static import):

    public static <T> Iterable<T> backwards(final List<T> list) {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return backwardsIterator(list);
            }
        };
    }

    private static <T> Iterator<T> backwardsIterator(List<T> list) {
        final ListIterator<T> iter = list.listIterator(list.size());
        return new Iterator<T>() {
            @Override
            public boolean hasNext() {
                return iter.hasPrevious();
            }

            @Override
            public T next() {
                return iter.previous();
            }

            @Override
            public void remove() {
                iter.remove();
            }
        };
    }
Advertisements
Categories: coding, java
  1. Warren
    • April 27, 2012 at 23:46

      Warren, this is interesting. Thanks for the link.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: