Java Iterable Size getSingle(Iterable it)

Here you can find the source of getSingle(Iterable it)

Description

Returns a single item from the Iterator.

License

Open Source License

Exception

Parameter Description
IllegalStateException an exception

Declaration

public static final <T> T getSingle(Iterable<T> it) 

Method Source Code


//package com.java2s;
import java.util.Iterator;

public class Main {
    /**/*from ww  w. j ava  2 s.c  om*/
     * Returns a single item from the Iterator.
     * If there's none, returns null.
     * If there are more, throws an IllegalStateException.
     *
     * @throws IllegalStateException
     */
    public static final <T> T getSingle(Iterable<T> it) {
        if (!it.iterator().hasNext())
            return null;

        final Iterator<T> iterator = it.iterator();
        T o = iterator.next();
        if (iterator.hasNext())
            throw new IllegalStateException("Found multiple items in iterator over " + o.getClass().getName());

        return o;
    }
}

Related

  1. countElements(Iterable pairs)
  2. getIterableSize(Iterable iterable)
  3. getSingleElementOrNull(Iterable coll)
  4. getSingleIfExist(Iterable iterable)
  5. getSingleOrNull(Iterable iterable)
  6. iterableSize(Iterable iterable)