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

org.codefilarete.tool.collection.IteratorIterator Maven / Gradle / Ivy

package org.codefilarete.tool.collection;

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

/**
 * An {@link Iterator} that iterates over other given {@link Iterator}s
 * 
 * @author Guillaume Mary
 */
public class IteratorIterator implements Iterator {
	
	private final Iterator> iterables;
	
	private Iterator currentIterator;
	
	@SafeVarargs // method body doesn't handle improperly varargs parameter so it would generate ClassCastException
	public IteratorIterator(Iterator ... iterables) {
		// we wrap given iterator array into an array of iterables, no very cleanly done but it's a very local usage.
		this(new Iterator>() {
			
			private final Iterator> delegate = new ArrayIterator<>(iterables);
			
			@Override
			public boolean hasNext() {
				return delegate.hasNext();
			}
			
			@Override
			public Iterable next() {
				return delegate::next;
			}
		});
	}
	
	@SafeVarargs // method body doesn't handle improperly varargs parameter so it would generate ClassCastException
	public IteratorIterator(Iterable ... iterables) {
		this(new ArrayIterator<>(iterables));
	}
	
	public IteratorIterator(Iterable> iterables) {
		this(iterables.iterator());
	}
	
	public IteratorIterator(Iterator> iterables) {
		this.iterables = iterables;
	}
	
	@Override
	public boolean hasNext() {
		if (currentIterator == null || !currentIterator.hasNext()) {
			boolean found = false;
			while(!found) {
				if (iterables.hasNext()) {
					currentIterator = iterables.next().iterator();
					found = currentIterator.hasNext();
				} else {
					return false;
				}
			}
		}
		// here currentIterator != null && currentIterator.hasNext() or found = true => both conditions are always true
		return true;
	}
	
	@Override
	public E next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		return currentIterator.next();
	}
	
	@Override
	public void remove() {
		currentIterator.remove();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy