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

com.databasesandlife.util.CompositeIterable Maven / Gradle / Ivy

There is a newer version: 21.0.1
Show newest version
package com.databasesandlife.util;

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

/**
 * Wraps a number of iterables into a single iterable.
 * This is especially useful when the iterables themselves are futures.
 * 
 * @param  The objects to be iterated over
 * @author This source is copyright Adrian Smith and licensed under the LGPL 3.
 * @see Project on GitHub
 */
public class CompositeIterable implements Iterable {
    
    Iterable> iterables;
    
    class I implements Iterator {
        Iterator currentIteratorWithinIterable; // null means finished
        Iterator> iteratorThroughIterables;
        
        public I() {
            iteratorThroughIterables = iterables.iterator();
            if (iteratorThroughIterables.hasNext()) currentIteratorWithinIterable = iteratorThroughIterables.next().iterator();
            else currentIteratorWithinIterable = null;
        }
        
        @Override public boolean hasNext() {
            while (currentIteratorWithinIterable != null && ! currentIteratorWithinIterable.hasNext()) {
                if (iteratorThroughIterables.hasNext()) currentIteratorWithinIterable = iteratorThroughIterables.next().iterator();
                else currentIteratorWithinIterable = null;
            }
            return currentIteratorWithinIterable != null;
        }
        
        @Override public T next() {
            if ( ! hasNext()) throw new NoSuchElementException();
            return currentIteratorWithinIterable.next();
        }

        @Override public void remove() { throw new UnsupportedOperationException(); }
    }
    
    public CompositeIterable(Iterable> iterables) {
        this.iterables = iterables;
    }

    @Override public Iterator iterator() {
        return new I();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy