All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jnape.palatable.lambda.iterators.CyclicIterator Maven / Gradle / Ivy

There is a newer version: 5.5.0
Show newest version
package com.jnape.palatable.lambda.iterators;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

public class CyclicIterator extends InfiniteIterator {
    private final Iterator     iterator;
    private final ListIterator doublyLinkedIterator;

    public CyclicIterator(Iterator iterator) {
        this.iterator = iterator;
        doublyLinkedIterator = new ArrayList().listIterator();
    }

    @Override
    public A next() {
        return iterator.hasNext() ? continueInitialIteration() : continueCachedIteration();
    }

    private A continueCachedIteration() {
        if (!doublyLinkedIterator.hasNext())
            while (doublyLinkedIterator.hasPrevious())
                doublyLinkedIterator.previous();

        return doublyLinkedIterator.next();
    }

    private A continueInitialIteration() {
        A next = iterator.next();
        doublyLinkedIterator.add(next);
        return next;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy