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

be.bagofwords.iterator.IteratorOfIterables Maven / Gradle / Ivy

package be.bagofwords.iterator;

import org.apache.commons.lang3.mutable.MutableInt;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class IteratorOfIterables implements Iterator {

    private Iterator> intIterator;
    private Iterator iterator;

    public IteratorOfIterables(Iterator> intIterator) {
        initialize(intIterator);
    }

    public IteratorOfIterables(final Iterable... iterables) {
        this(Arrays.asList(iterables));
    }

    public IteratorOfIterables(final List> iterables) {
        final MutableInt ind = new MutableInt(0);
        initialize(new Iterator>() {
            @Override
            public boolean hasNext() {
                return ind.intValue() < iterables.size();
            }

            @Override
            public Iterable next() {
                Iterable next = iterables.get(ind.intValue());
                ind.increment();
                return next;
            }

            @Override
            public void remove() {
                throw new RuntimeException("Not possible with multiple iterables...");
            }
        });
    }

    private void initialize(Iterator> intIterator) {
        this.intIterator = intIterator;
        findNextIterator();
    }

    private void findNextIterator() {
        Iterator nextIterator = null;
        while ((nextIterator == null || !nextIterator.hasNext()) && this.intIterator.hasNext()) {
            nextIterator = intIterator.next().iterator();
        }
        if (nextIterator != null && nextIterator.hasNext()) {
            this.iterator = nextIterator;
        } else {
            this.iterator = null;
        }
    }

    @Override
    public boolean hasNext() {
        return iterator != null && iterator.hasNext();
    }

    @Override
    public T next() {
        T nextVal = iterator.next();
        if (!iterator.hasNext()) {
            findNextIterator();
        }
        return nextVal;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy