jodd.util.collection.CompositeIterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jodd-core Show documentation
Show all versions of jodd-core Show documentation
Jodd Core tools and utilities, including type converters, JDateTime, cache etc.
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.
package jodd.util.collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.ArrayList;
/**
* Iterator that combines multiple iterators.
*/
public class CompositeIterator implements Iterator {
protected final List> allIterators = new ArrayList>();
/**
* Creates new composite iterator.
* Iterators may be added using the {@link #add(Iterator)} method.
*/
public CompositeIterator() {
}
/**
* Creates new composite iterator with provided iterators.
*/
public CompositeIterator(Iterator... iterators) {
for (Iterator iterator : iterators) {
add(iterator);
}
}
/**
* Adds an iterator to this composite.
*/
public void add(Iterator iterator) {
if (allIterators.contains(iterator)) {
throw new IllegalArgumentException("Duplicate iterator");
}
allIterators.add(iterator);
}
// ---------------------------------------------------------------- interface
protected int currentIterator = -1;
/**
* Returns true
if next element is available.
*/
public boolean hasNext() {
if (currentIterator == -1) {
currentIterator = 0;
}
for (int i = currentIterator; i < allIterators.size(); i++) {
Iterator iterator = allIterators.get(i);
if (iterator.hasNext()) {
currentIterator = i;
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
public T next() {
if (hasNext() == false) {
throw new NoSuchElementException();
}
return allIterators.get(currentIterator).next();
}
/**
* {@inheritDoc}
*/
public void remove() {
if (currentIterator == -1) {
throw new IllegalStateException("next() has not yet been called");
}
allIterators.get(currentIterator).remove();
}
}