Java Collection First getFirstItem(Collection c)

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

Description

Return the first item from a collection using the most efficient method possible.

License

Open Source License

Parameter

Parameter Description
c The Collection.

Exception

Parameter Description

Return

the first element of a Collection.

Declaration

public static Object getFirstItem(Collection c) 

Method Source Code

//package com.java2s;
/* $Id$//  w ww  .ja  va2 s .  c  o m
 *******************************************************************************
 * Copyright (c) 2009 Contributors - see below
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Bob Tarling
 *******************************************************************************
 */

import java.util.Collection;
import java.util.List;

public class Main {
    /**
     * Return the first item from a collection using the most efficient
     * method possible.
     *
     * @param c The Collection.
     * @return the first element of a Collection.
     * @throws java.util.NoSuchElementException if the collection is empty.
     */
    public static Object getFirstItem(Collection c) {
        if (c instanceof List) {
            return ((List) c).get(0);
        }
        return c.iterator().next();
    }
}

Related

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