Can I chain Iterator
s in Java 8, e.g. using external libraries such as Apache? Something to the effect of
Iterator
In my example, compositeIterator
would iterate over items of iteratorOne
(for as long as it hasNext()
) and then iteratorTwo
Spring Framework has this, but I don’t want the project to have a dependency on Spring just for some trivial utility. I don’t feel like copy-pasting either
package org.springframework.util;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
public class CompositeIterator implements Iterator {
private List> iterators = new LinkedList();
private boolean inUse = false;
public CompositeIterator() {
}
public void add(Iterator iterator) {
Assert.state(!this.inUse, "You can no longer add iterator to a composite iterator that's already in use");
if (this.iterators.contains(iterator)) {
throw new IllegalArgumentException("You cannot add the same iterator twice");
} else {
this.iterators.add(iterator);
}
}
public boolean hasNext() {
this.inUse = true;
Iterator> it = this.iterators.iterator();
while(it.hasNext()) {
if (((Iterator)it.next()).hasNext()) {
return true;
}
}
return false;
}
public E next() {
this.inUse = true;
Iterator> it = this.iterators.iterator();
while(it.hasNext()) {
Iterator iterator = (Iterator)it.next();
if (iterator.hasNext()) {
return iterator.next();
}
}
throw new NoSuchElementException("Exhaused all iterators");
}
public void remove() {
throw new UnsupportedOperationException("Remove is not supported");
}
}