Java Collection First getFirstAndOnly(Collection c)

Here you can find the source of getFirstAndOnly(Collection c)

Description

get First And Only

License

Apache License

Declaration

public static <T> T getFirstAndOnly(Collection<T> c) 

Method Source Code

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

import java.util.Collection;

public class Main {
    public static <T> T getFirstAndOnly(Collection<T> c) {
        if (c.size() != 1) {
            throw new Error("Size must be 1 but was " + c.size());
        }/* ww w .  j  a va 2 s  .c om*/
        return getFirst(c);
    }

    @SuppressWarnings("rawtypes")
    public static int size(Iterable<?> i) {
        if (i instanceof Collection) {
            return ((Collection) i).size();
        }
        int size = 0;
        for (@SuppressWarnings("unused")
        Object o : i) {
            size++;
        }
        return size;
    }

    public static <T> T getFirst(Iterable<T> ts) {
        for (T t : ts) {
            return t;
        }
        throw new Error("collection has no first element");
    }
}

Related

  1. getFirst(Collection l)
  2. getFirst(Collection set)
  3. getFirst(Collection set, boolean remove)
  4. getFirst(Collection ts)
  5. getFirst(final Collection collection)
  6. getFirstClassOfType(Collection l, Class type)
  7. getFirstElement(Collection coll)
  8. getFirstElement(Collection collection, T defaultValue)
  9. getFirstElementOrNull(Collection collection)