Java List First Item getFirstOrNull(List elements)

Here you can find the source of getFirstOrNull(List elements)

Description

get First Or Null

License

Open Source License

Return

the first element from , or null if is empty.

Declaration

public static <T> T getFirstOrNull(List<T> elements) 

Method Source Code

//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());
    }
}

Related

  1. getFirstLeaf(List aList)
  2. getFirstNameIndex(List list)
  3. getFirstNonEmptyIndex(final List> list)
  4. getFirstObject(List valueList)
  5. getFirstOccurNic(List nics, String line)
  6. getFirstOrNull(List list)
  7. getFirstRowMatch(List list, int columnIndex, T value)
  8. getFirstRowResults(List> llo, String reason)
  9. getFirstString(Object list)

  10. HOME | Copyright © www.java2s.com 2016