Java Utililty Methods Collection First

List of utility methods to do Collection First

Description

The list of methods to do Collection First are organized into topic(s).

Method

TgetFirst(Collection set, boolean remove)
get First
Iterator<T> iterator = set.iterator();
if (!iterator.hasNext()) {
    throw new IllegalStateException("The set is empty");
T first = iterator.next();
if (remove) {
    iterator.remove();
return first;
TgetFirst(Collection ts)
get First
final Iterator<T> it = ts.iterator();
return it.hasNext() ? it.next() : null;
TgetFirst(final Collection collection)
get First
return collection == null ? null : collection.iterator().next();
TgetFirstAndOnly(Collection c)
get First And Only
if (c.size() != 1) {
    throw new Error("Size must be 1 but was " + c.size());
return getFirst(c);
UgetFirstClassOfType(Collection l, Class type)
Get the first class of type U in the collection
for (T o : l) {
    if (type.isInstance(o)) {
        return type.cast(o);
return null;
TgetFirstElement(Collection coll)
INTERNAL: Gets the first object in the collection.
if (coll instanceof List)
    try {
        return ((List<T>) coll).get(0);
    } catch (IndexOutOfBoundsException e) {
        throw new NoSuchElementException();
else
    return coll.iterator().next();
...
TgetFirstElement(Collection collection, T defaultValue)
get First Element
T elem = defaultValue;
if (collection != null && !collection.isEmpty()) {
    if (List.class.isAssignableFrom(collection.getClass())) {
        elem = ((List<T>) collection).get(0);
    } else {
        for (T item : collection) {
            elem = item;
            break;
...
EgetFirstElementOrNull(Collection collection)
returns the first element of a collection or null if the collection is empty.
if (collection.isEmpty()) {
    return null;
} else {
    return collection.iterator().next();
TgetFirstElementOrNull(Collection coll)
get First Element Or Null
if (coll == null || coll.isEmpty())
    return null;
return coll.iterator().next();
ObjectgetFirstItem(Collection c)
Return the first item from a collection using the most efficient method possible.
if (c instanceof List) {
    return ((List) c).get(0);
return c.iterator().next();