Java Collection First getCollectionFirstElement( final Collection collection)

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

Description

Gets the first element of a collection, if it exist.

License

Open Source License

Parameter

Parameter Description
collection the Collection where to get the first item from, mustn't be <code>null</code>.

Return

the first element of the collection, if it exist, otherwise returns null .

Declaration

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

Method Source Code

//package com.java2s;
/*//from  ww  w.j  a  v a2  s  .c  o  m
 CollectionUtils.java
 Creation date : 11/10/2013
 Copyright ? Benjamin Croizet (graffity2199@yahoo.fr)

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 or GNU Lesser General Public License as published by the
 Free Software Foundation; either version 3 of the License,
 or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received copies of the GNU General Public License
 and GNU Lesser General Public License along with this program;
 if not, write to the Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 http://www.fsf.org/licensing/licenses/gpl.html
 http://www.gnu.org/licenses/lgpl.html
 */

import java.util.ArrayList;
import java.util.Collection;

public class Main {
    /**
     * Gets the first element of a collection, if it exist.
     *
     * @param collection
     *            the {@link Collection} where to get the first item from, mustn't be
     *            <code>null</code>.
     * @return the first element of the collection, if it exist, otherwise returns <code>null</code>
     *         .
     * @since 1.3.0
     */
    public static <T> T getCollectionFirstElement(
            final Collection<T> collection) {
        T result = null;

        if (collection.isEmpty() == false) {
            result = new ArrayList<T>(collection).get(0);
        }

        return result;
    }
}

Related

  1. firstNonEmpty(Collection... collections)
  2. firstNonNull(Collection collection)
  3. firstOrThat(Collection collection, T that)
  4. firstValue(Class type, Collection values)
  5. GET_FIRST_ELEMENT(Collection coll)
  6. getFirst(Collection c)
  7. getFirst(Collection c)
  8. getFirst(Collection collection)
  9. getFirst(Collection bag)