Skip to content

Instantly share code, notes, and snippets.

@ChristianGaertner
Last active December 23, 2015 00:39
Show Gist options
  • Select an option

  • Save ChristianGaertner/6554814 to your computer and use it in GitHub Desktop.

Select an option

Save ChristianGaertner/6554814 to your computer and use it in GitHub Desktop.
Reverse Iterator for ArrayLists and the like. Use it in your foreach loops
public class Reversed<T> implements Iterable<T> {
private final List<T> org;
public Reversed(List<T> original) {
org = original;
}
public Iterator<T> iterator() {
final ListIterator<T> i = org.listIterator(org.size());
return new Iterator<T>() {
public boolean hasNext() {
return i.hasPrevious();
}
public T next() {
return i.previous();
}
public void remove() {
i.remove();
}
};
}
public static <T> Reversed<T> reversed(List<T> original) {
return new Reversed<T>(original);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment