Search in sources :

Example 1 with Iterators

use of java8.util.Iterators in project streamsupport by stefan-zobel.

the class Spliterators method iterator.

// Iterators from Spliterators
/**
 * Creates an {@code Iterator} from a {@code Spliterator}.
 *
 * <p>Traversal of elements should be accomplished through the iterator.
 * The behaviour of traversal is undefined if the spliterator is operated
 * after the iterator is returned.
 *
 * @param <T> Type of elements
 * @param spliterator The spliterator
 * @return An iterator
 * @throws NullPointerException if the given spliterator is {@code null}
 */
public static <T> Iterator<T> iterator(Spliterator<? extends T> spliterator) {
    Objects.requireNonNull(spliterator);
    class Adapter implements Iterator<T>, Consumer<T> {

        boolean valueReady = false;

        T nextElement;

        @Override
        public void accept(T t) {
            valueReady = true;
            nextElement = t;
        }

        @Override
        public boolean hasNext() {
            if (!valueReady)
                spliterator.tryAdvance(this);
            return valueReady;
        }

        @Override
        public T next() {
            if (!valueReady && !hasNext())
                throw new NoSuchElementException();
            else {
                valueReady = false;
                return nextElement;
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("remove");
        }
    }
    return new Adapter();
}
Also used : LongConsumer(java8.util.function.LongConsumer) IntConsumer(java8.util.function.IntConsumer) Consumer(java8.util.function.Consumer) DoubleConsumer(java8.util.function.DoubleConsumer) Iterator(java.util.Iterator) NoSuchElementException(java.util.NoSuchElementException)

Aggregations

Iterator (java.util.Iterator)1 NoSuchElementException (java.util.NoSuchElementException)1 Consumer (java8.util.function.Consumer)1 DoubleConsumer (java8.util.function.DoubleConsumer)1 IntConsumer (java8.util.function.IntConsumer)1 LongConsumer (java8.util.function.LongConsumer)1