Multirator : an iterator that iterates over other iterators
See original GitHub issueOriginal issue created by thierryler on 2014-04-15 at 11:29 AM
Hello,
Would you like to add a multirator in Guava ? A multirator (named choosen in 5 minutes) is an iterator that encapsulates other iterators. I gives the next element based on the next elements of the other iterators.
Here is what i looks like :
public interface Multirator<E> extends Iterator<E>, Iterable<E> { void add(final Iterator<E>… iterators); void add(final Iterable<E>… iterables); }
I wrote a first implementation who choose the next element as the smallest available :
public class SortedPeekingMultirator<E extends Comparable<E>> implements Multirator<E> {
private final List<PeekingIterator<E>> iterators = new ArrayList<>();
/* Constructors */
@SafeVarargs
public SortedPeekingMultirator(final Iterator<E>... iterators) {
add(iterators);
}
@SafeVarargs
public SortedPeekingMultirator(final Iterable<E>... iterables) {
add(iterables);
}
/* From Multirator.java */
@SuppressWarnings("unchecked")
@Override
public void add(final Iterator<E>... iterators) {
for (final Iterator<E> iter : iterators) {
final PeekingIterator<E> pi = Iterators.peekingIterator(iter);
this.iterators.add(pi);
}
}
@SuppressWarnings("unchecked")
@Override
public void add(final Iterable<E>... iterables) {
for (final Iterable<E> iterable : iterables) {
add(iterable.iterator());
}
}
/* From Iterator.java */
@Override
public boolean hasNext() {
for (final PeekingIterator<E> pi : iterators) {
if (pi.hasNext()) {
return true;
}
}
return false;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E smallest = null;
int pos = 0;
int i = 0;
for (final PeekingIterator<E> pi : iterators) {
if (!pi.hasNext()) {
i++;
continue;
}
final E elt = pi.peek();
if (smallest == null) {
smallest = elt;
pos = i++;
continue;
}
if (smallest.compareTo(elt) > 0) {
smallest = elt;
pos = i++;
}
}
// next
iterators.get(pos).next();
return smallest;
}
}
Please have a look at the attached files for complete source code and tests.
What do you think about this multirator ?
Thierry
Issue Analytics
- State:
- Created 9 years ago
- Reactions:1
- Comments:5 (1 by maintainers)
Top GitHub Comments
Original comment posted by thierryler on 2014-04-15 at 02:00 PM
Well I was not aware of the method “concat”. It looks great.
But I would say that it does not provide exactly the same thing. With concat, you can not specify the order for example. And it works with copies.
Closing this in favor of the alternatives presented.