Java Collection First getFirstOrNull(final Collection collection)

Here you can find the source of getFirstOrNull(final Collection collection)

Description

Return either the first element when the collection is not null and empty or null.

License

Apache License

Parameter

Parameter Description
collection the collection to handle.

Return

the first element when the collection is not null and empty or null.

Declaration

public static <T> T getFirstOrNull(final Collection<T> collection) 

Method Source Code

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

import java.util.Collection;

import java.util.List;

public class Main {
    /**//  ww  w .ja  va2 s  .c  o  m
     * Return either the first element when the collection is not null and empty
     * or null.
     * 
     * @param collection
     *            the collection to handle.
     * @return the first element when the collection is not null and empty or
     *         null.
     */
    public static <T> T getFirstOrNull(final Collection<T> collection) {

        if (isEmpty(collection)) {
            return null;
        }
        if (collection instanceof List) {
            return ((List<T>) collection).get(0);
        } else {
            return collection.iterator().next();
        }
    }

    /**
     * Returns true if the collection is null or empty; false otherwise.
     * 
     * @param collection
     *            the collection to be tested.
     * @return true if the collection is null or empty; false otherwise.
     */
    public static boolean isEmpty(final Collection<?> collection) {

        return collection == null || collection.isEmpty();
    }
}

Related

  1. getFirstItem(Collection c)
  2. getFirstItemInCollection(Collection collection)
  3. getFirstN(Collection objects, int n)
  4. getFirstNonNull(Collection c)
  5. getFirstNotNullValue(final Collection collection)
  6. getFirstSortedItem( Collection items, T defaultValue)
  7. getUnionSize(Collection firstCollection, Collection secondCollection)
  8. intersect(Collection firstSet, Collection secondSet)
  9. nullSafeFirstElement(Collection collection)