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

ch.obermuhlner.scriptengine.java.util.CompositeIterator Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
package ch.obermuhlner.scriptengine.java.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * A {@link Iterator} that will iterate over several iterators.
 *
 * @param  the type of elements returned by this iterator
 */
public class CompositeIterator implements Iterator {
    private final Iterator[] iterators;
    private int iteratorIndex = 0;

    /**
     * Creates a {@link CompositeIterator} over the specified iterators.
     *
     * @param iterators the {@link Iterator}s
     */
    public CompositeIterator(Iterator... iterators) {
        this.iterators = iterators;
    }

    @Override
    public boolean hasNext() {
        if (iteratorIndex >= iterators.length) {
            return false;
        }
        if (iterators[iteratorIndex].hasNext()) {
            return true;
        }
        iteratorIndex++;

        if (iteratorIndex >= iterators.length) {
            return false;
        }

        return iterators[iteratorIndex].hasNext();
    }

    @Override
    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        return iterators[iteratorIndex].next();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy