All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.javagimmicks.collections8.composite.CompositeIterator Maven / Gradle / Ivy

There is a newer version: 0.99-alpha1
Show newest version
package net.sf.javagimmicks.collections8.composite;

import static net.sf.javagimmicks.collections8.transformer.TransformerUtils.decorate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

class CompositeIterator implements Iterator
{
   protected final Iterator> _iterators;

   protected Iterator _currentIterator;
   protected Iterator _nextIterator;

   CompositeIterator(final List> iterators)
   {
      _iterators = iterators.iterator();

      findNextIterator();
   }

   static > CompositeIterator fromCollectionList(final List collections)
   {
      final List> iteratorList = new ArrayList>(decorate(collections,
            Collection::iterator));

      return new CompositeIterator(iteratorList);
   }

   @Override
   public boolean hasNext()
   {
      if (_currentIterator != null && _currentIterator.hasNext())
      {
         return true;
      }

      findNextIterator();
      return _nextIterator != null && _nextIterator.hasNext();
   }

   @Override
   public E next()
   {
      if (!hasNext())
      {
         throw new NoSuchElementException();
      }

      return moveNext();
   }

   @Override
   public void remove()
   {
      if (_currentIterator == null)
      {
         throw new IllegalStateException();
      }

      _currentIterator.remove();
   }

   protected void findNextIterator()
   {
      if (_nextIterator != null)
      {
         return;
      }

      while (_iterators.hasNext())
      {
         _nextIterator = _iterators.next();

         if (_nextIterator.hasNext())
         {
            break;
         }
      }
   }

   protected E moveNext()
   {
      if (_nextIterator != null)
      {
         _currentIterator = _nextIterator;
         _nextIterator = null;
      }

      return _currentIterator.next();
   }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy