Java Iterator singletonIterator(final T item)

Here you can find the source of singletonIterator(final T item)

Description

Returns a singleton iterator with a single item.

License

Apache License

Parameter

Parameter Description
T the item kind.
item the item.

Return

a singleton iterator with a single item.

Declaration

public static <T> Iterator<T> singletonIterator(final T item) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    /**/*from   w  w  w . jav  a 2 s  .  c  o m*/
     * Returns a singleton iterator with a single item.
     * 
     * @param <T> the item kind.
     * @param item the item.
     * @return a singleton iterator with a single item.
     */
    public static <T> Iterator<T> singletonIterator(final T item) {

        return new Iterator<T>() {

            private T _item = item;
            private boolean _hasItem = false;

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

            @Override
            public T next() {
                if (_hasItem) {
                    throw new NoSuchElementException();
                }
                _hasItem = true;
                return _item;
            }

            @Override
            public void remove() {
                if (!_hasItem) {
                    _hasItem = true;
                } else {
                    throw new NoSuchElementException();
                }
            }
        };
    }
}

Related

  1. shallowUnionColIter(Iterator> values)
  2. single(Iterator i)
  3. singleElementIterator(T element)
  4. singleOrDefault(Iterator iterator)
  5. singletonIterator(final Object item)
  6. singletonIterator(final T nullableValue)
  7. singletonIterator(final T t)
  8. size(Iterator iterator)
  9. splice(LinkedList list, Iterator iterator, LinkedList list2, V v)