Java Collection First getFirstItem(Collection collection)

Here you can find the source of getFirstItem(Collection collection)

Description

Get the 1st element of the collection.

License

Open Source License

Parameter

Parameter Description
collection a parameter

Declaration

public static <T> T getFirstItem(Collection<T> collection) 

Method Source Code


//package com.java2s;

import java.util.Collection;

import java.util.Map;

public class Main {
    /**//from   w  ww. j av  a2 s . c  o  m
     * Get the 1st element of the collection.
     * 
     * @param collection
     * @return
     */
    public static <T> T getFirstItem(Collection<T> collection) {
        if (isEmpty(collection)) {
            return null;
        }
        for (T item : collection) {
            return item;
        }
        return null;
    }

    /**
     * Check if the collection is empty.
     * 
     * @param collection
     * @return
     */
    public static boolean isEmpty(Collection<?> collection) {
        return collection == null || collection.size() == 0;
    }

    /**
     * Check if the map is empty.
     * 
     * @param map
     * @return
     */
    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.size() == 0;
    }
}

Related

  1. getFirstElement(Collection coll)
  2. getFirstElement(Collection collection, T defaultValue)
  3. getFirstElementOrNull(Collection collection)
  4. getFirstElementOrNull(Collection coll)
  5. getFirstItem(Collection c)
  6. getFirstItem(Collection c)
  7. getFirstItemInCollection(Collection collection)
  8. getFirstN(Collection objects, int n)
  9. getFirstNonNull(Collection c)