Returns the last 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 last 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(getLastElement(l));
    }/*from  w w w.java 2  s  . com*/

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

        return l.get(l.size() - 1);
    }
}

Related Tutorials