Java examples for java.util:Iterable Element
Returns the first element from the given Iterable
/******************************************************************************* * 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 w w w. j ava 2s. c om*/ * Technical University Darmstadt - initial API and implementation and/or initial documentation *******************************************************************************/ //package com.java2s; 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. } } }