package uebung09.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class SkipNullIterator<T> implements Iterator<T>{
    private final Iterator<T> iterator;
    private T nextItem;
    private boolean hasNext;

    public SkipNullIterator(Iterator<T> iterator) {
        this.iterator = iterator;
        advance();
    }

    private void advance() {
        hasNext = false;
        nextItem = null;
        while (iterator.hasNext()) {
            nextItem = iterator.next();
            if (nextItem != null) {
                hasNext = true;
                break;
            }
        }
    }

    @Override
    public boolean hasNext() {
        return hasNext;
    }

    @Override
    public T next() {
        if (!hasNext) {
            throw new NoSuchElementException();
        }
        T currentItem = nextItem;
        advance();
        return currentItem;
    }
}
