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

com.github.basking2.sdsai.itrex.iterators.HeadIterator Maven / Gradle / Ivy

There is a newer version: 1.1.23
Show newest version
package com.github.basking2.sdsai.itrex.iterators;

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

/**
 * Return the first N elements of another iterator.
 *
 * This is used to implement the {@link PagingIterator}.
 *
 * @param  The type.
 */
public class HeadIterator implements Iterator {
    private int left;
    private final Iterator iterator;

    public HeadIterator(final int n, final Iterator iterator) {
        this.left = n;
        this.iterator = iterator;
    }

    public HeadIterator(final Iterator iterator) {
        this(1, iterator);
    }

    @Override
    public boolean hasNext() {
        return left > 0 && iterator.hasNext();
    }

    @Override
    public T next() {
        if (left < 1) {
            throw new NoSuchElementException("No elements left in HeadIterator.");
        }

        left--;

        return iterator.next();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy