Here you can find the source of getFirstOrNull(List
null
if is empty.
public static <T> T getFirstOrNull(List<T> elements)
//package com.java2s; /******************************************************************************* * Copyright (c) 2011 Google, Inc.//from ww w . j a va 2 s. co m * 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: * Google, Inc. - initial API and implementation *******************************************************************************/ import java.util.List; public class Main { /** * @return the first element from {@link List} , or <code>null</code> if {@link List} is empty. */ public static <T> T getFirstOrNull(List<T> elements) { return elements.isEmpty() ? null : elements.get(0); } /** * @return first element of required type, <code>null</code> if not found. */ @SuppressWarnings("unchecked") public static <T> T get(Class<T> clazz, Object... objects) { for (Object object : objects) { if (isAssignable(clazz, object)) { return (T) object; } } return null; } /** * @return first element of required type, <code>null</code> if not found. */ @SuppressWarnings("unchecked") public static <T> T get(Class<T> clazz, List<?> objects) { for (Object object : objects) { if (isAssignable(clazz, object)) { return (T) object; } } return null; } /** * @return <code>true</code> object can be casted to given class. */ private static boolean isAssignable(Class<?> clazz, Object object) { return object != null && clazz.isAssignableFrom(object.getClass()); } }