com.jnape.palatable.lambda.iterators.ReversingIterator Maven / Gradle / Ivy
package com.jnape.palatable.lambda.iterators;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ReversingIterator extends ImmutableIterator {
private final Iterator as;
private final ListIterator reversingIterator;
public ReversingIterator(Iterator as) {
this.as = as;
reversingIterator = new ArrayList().listIterator();
}
@Override
public boolean hasNext() {
return readyToReverse() ? reversingIterator.hasPrevious() : as.hasNext();
}
@Override
public A next() {
if (!readyToReverse())
prepareForReversal();
return reversingIterator.previous();
}
private void prepareForReversal() {
while (as.hasNext())
reversingIterator.add(as.next());
}
private boolean readyToReverse() {
return reversingIterator.hasNext() || reversingIterator.hasPrevious();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy