Java Iterable First getFirst(Iterable iterable)

Here you can find the source of getFirst(Iterable iterable)

Description

Returns the first element from the given Iterable .

License

Open Source License

Parameter

Parameter Description
iterable The Iterable to get first element from.

Return

The first element or null if no element is available.

Declaration

public static <T> T getFirst(Iterable<T> iterable) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 Karlsruhe Institute of Technology, Germany
 *                    Technical University Darmstadt, Germany
 *                    Chalmers University of Technology, Sweden
 * 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:/*from   www.j ava2s.  com*/
 *    Technical University Darmstadt - initial API and implementation and/or initial documentation
 *******************************************************************************/

import java.util.Iterator;

import java.util.NoSuchElementException;

public class Main {
    /**
     * Returns the first element from the given {@link Iterable}.
     * @param iterable The {@link Iterable} to get first element from.
     * @return The first element or {@code null} if no element is available.
     */
    public static <T> T getFirst(Iterable<T> iterable) {
        try {
            if (iterable != null) {
                Iterator<T> iter = iterable.iterator();
                return iter.next();
            } else {
                return null;
            }
        } catch (NoSuchElementException e) {
            return null; // Iterable must be empty.
        }
    }
}

Related

  1. firstOrNull(Iterable iterable)
  2. getFirst(final Iterable iterable)
  3. getFirst(final Iterable iterable)
  4. getFirst(Iterable iterable)
  5. getFirst(Iterable c)
  6. getFirst(Iterable iterable)
  7. getFirst(Iterable iterable)
  8. getFirst(Iterable iterable, T defaultValue)
  9. getFirstElement(Object maybeIterable)