Returns the first element of a list or null if the list is null or empty. - Java java.util

Java examples for java.util:List First Element

Description

Returns the first element of a list or null if the list is null or empty.

Demo Code


//package com.java2s;

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        List l = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(getFirstElement(l));
    }/*from   ww  w.  ja va 2  s.co m*/

    /**
     * Returns the first element of a list or null if the list
     * is null or empty.
     * 
     * @param l the list in which to find the first element
     * @return Object the first element of the list
     */
    public static Object getFirstElement(List l) {
        // Return null if list is null or empty
        if (l == null || l.isEmpty())
            return null;

        return l.get(0);
    }
}

Related Tutorials