Provides the first item from a list, unless the list is null or empty, in which case null is returned. - Java java.util

Java examples for java.util:List Operation

Description

Provides the first item from a list, unless the list is null or empty, in which case null is returned.

Demo Code


//package com.java2s;

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        List list = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(first(list));
    }//from  w ww .  j  a v  a2s  . c  o m

    /**
     * Provides the first item from a list, unless the list is <tt>null</tt> or empty, in which case <tt>null</tt> is
     * returned. This is useful because the behaviour of List.get(0) is to throw an exception is the list is empty.
     *
     * @param  list The list to take the first item from.
     * @param  <T>  The type of the items in the list.
     *
     * @return The first item from a list, unless the list is <tt>null</tt> or empty, in which case <tt>null</tt> is
     *         returned.
     */
    public static <T> T first(List<T> list) {
        return list.isEmpty() || list == null ? null : list.get(0);
    }
}

Related Tutorials