001package org.biopax.paxtools.util; 002 003import java.util.Collection; 004import java.util.Iterator; 005import java.util.NoSuchElementException; 006 007/** 008 * A composite iterator that iterates over multiple iterators. 009 * @param <T> Base class type which all subiterator's type must extend from. 010 */ 011public class CompositeIterator<T> implements Iterator<T> 012{ 013 Iterator<? extends Collection<? extends T>> collectionIterator; 014 Iterator<? extends T> currentIterator; 015 016 /** 017 * This constructor creates an iterator instance from a set of collections 018 * @param collections to be iterated over. 019 */ 020 public CompositeIterator(Collection<? extends Collection<? extends T>> collections) 021 { 022 collectionIterator = collections.iterator(); 023 currentIterator = getNextSet(); 024 025 } 026 027 @Override 028 public boolean hasNext() { 029 if (currentIterator == null) { 030 return false; 031 } else if (!currentIterator.hasNext()) 032 { 033 currentIterator = getNextSet(); 034 return this.hasNext(); 035 } 036 else return true; 037 } 038 039 @Override 040 public T next() { 041 if (this.hasNext()) { 042 return currentIterator.next(); 043 } else { 044 throw new NoSuchElementException(); 045 } 046 } 047 048 @Override 049 public void remove() { 050 throw new UnsupportedOperationException(); 051 } 052 053 private Iterator<? extends T> getNextSet() { 054 return collectionIterator.hasNext() ? collectionIterator.next().iterator() : null; 055 } 056 057} 058 059