Java Utililty Methods Iterable Size

List of utility methods to do Iterable Size

Description

The list of methods to do Iterable Size are organized into topic(s).

Method

intcountElements(Iterable pairs)
count Elements
if (pairs instanceof List) {
    return ((List<?>) pairs).size();
} else {
    throw new IllegalArgumentException("Cannot determine split size from split result.");
intgetIterableSize(Iterable iterable)
get Iterable Size
if (iterable instanceof Collection<?>) {
    return ((Collection<?>) iterable).size();
} else {
    Iterator<?> it = iterable.iterator();
    int i = 0;
    while (it.hasNext()) {
        i++;
    return i;
TgetSingle(Iterable it)
Returns a single item from the Iterator.
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;
TgetSingleElementOrNull(Iterable coll)
get Single Element Or Null
if (coll == null)
    return null;
Iterator<T> iterator = coll.iterator();
T firstElement = iterator.next();
return iterator.hasNext() ? null : firstElement;
TgetSingleIfExist(Iterable iterable)
get Single If Exist
if (iterable == null)
    return null;
final Iterator<? extends T> iter = iterable.iterator();
if (!iter.hasNext())
    return null;
final T result = iter.next();
if (iter.hasNext()) {
    throw new IllegalArgumentException("More than (expected) one element in " + iterable);
...
TgetSingleOrNull(Iterable iterable)
Get a single element from iterable.
return getSingleOrNull(iterable.iterator());
intiterableSize(Iterable iterable)
iterable Size
int result = 0;
for (Object eleme : iterable) {
    result++;
return result;
intiterableSize(Iterable itrbl)
Computes, in linear time, the length of an Iterable.
int size = 0;
for (Iterator<E> iter = itrbl.iterator(); iter.hasNext();) {
    iter.next();
    size++;
return size;
booleaniterableSizeEq(Iterable itrbl, int k)
Checks whether the iterable itrbl has exactly k elements.
Iterator<E> it = itrbl.iterator();
for (int i = 0; i < k; i++) {
    if (!it.hasNext())
        return false;
    it.next();
return !it.hasNext();
TsingleOrNull(Iterable iterable)
A single item or null
Iterator<T> i = iterable.iterator();
if (i.hasNext()) {
    return i.next();
return null;