001package org.biojava.utils;
002
003import java.util.Collection;
004import java.util.Collections;
005import java.util.Iterator;
006
007/**
008 *
009 *
010 * @author Matthew Pocock
011 */
012public class MergingIterator
013        implements Iterator
014{
015  private final Iterator sourceIt;
016  private Iterator currentIt;
017  private Object nextVal;
018
019  public MergingIterator(Iterator sourceIt) {
020    this.sourceIt = sourceIt;
021    currentIt = Collections.EMPTY_SET.iterator();
022    nextVal = findNextVal();
023  }
024
025  public boolean hasNext() {
026    return nextVal != null;
027  }
028
029  public Object next() {
030    Object val = nextVal;
031    nextVal = findNextVal();
032    return val;
033  }
034
035  public void remove() {
036    throw new UnsupportedOperationException();
037  }
038
039  private Object findNextVal() {
040    while(true) {
041      if(!currentIt.hasNext()) {
042        if(!sourceIt.hasNext()) {
043          return null;
044        }
045
046        currentIt = ((Collection) (sourceIt.next())).iterator();
047
048        continue;
049      } else {
050        return currentIt.next();
051      }
052    }
053  }
054}