Iterator from Supplier

Creating an Iterator can be one step towards creating a stream from some resource. SupplierIterator takes only a Supplier and uses buffer for the next value. Example is inspired by java.io.BufferedReader.lines() method.

public class SupplierIterator<T> implements Iterator<T> {
   private T buffer = null;
   private Supplier<T> supplier;

   public SupplierIterator(Supplier<T> supplier) {
      this.supplier = supplier;
   }

   @Override
   public boolean hasNext() {
      return (buffer != null) ||
         (buffer = supplier.get()) != null;
   }

   @Override
   public T next() {
      if (hasNext()) {
         T next = buffer;
         buffer = null;
         return next;
      } else {
         throw new NoSuchElementException();
      }
   }
}

No comments:

Post a Comment