Created
February 25, 2017 12:51
-
-
Save hector6872/ba03e1479e4395687eb7c6fc74ca72bd to your computer and use it in GitHub Desktop.
ReverseIterable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class ReverseIterable { | |
private ReverseIterable() { | |
} | |
public static <T> Iterable<T> reverse(final List<T> list) { | |
return new ListReverseIterable<>(list); | |
} | |
private static class ListReverseIterable<T> implements Iterable<T> { | |
private final List<T> list; | |
ListReverseIterable(final List<T> list) { | |
this.list = list; | |
} | |
public Iterator<T> iterator() { | |
return new Iterator<T>() { | |
final ListIterator<T> it = list.listIterator(list.size()); | |
public boolean hasNext() { | |
return it.hasPrevious(); | |
} | |
public T next() { | |
return it.previous(); | |
} | |
public void remove() { | |
it.remove(); | |
} | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for (Item item : ReverseIterable.reverse(list)) {
// do stuff
}