Java Collection Last getLast(Collection c)

Here you can find the source of getLast(Collection c)

Description

Returns the last element in a collection (by exhausting its iterator in case it is not a list).

License

Open Source License

Exception

Parameter Description

Declaration

public static Object getLast(Collection c) 

Method Source Code

//package com.java2s;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main {
    /**/*from   w w w.j a  v a2 s .c  o  m*/
     * Returns the last element in a collection (by exhausting its iterator in
     * case it is not a list).
     * 
     * @throws java.util.NoSuchElementException
     *           if collection is empty.
     */
    public static Object getLast(Collection c) {
        if (c instanceof List)
            return getLast((List) c);
        Object result = null;
        Iterator it = c.iterator();
        do { // we use 'do' to ensure next() is called at least once, throwing
             // exception if c is empty.
            result = it.next();
        } while (it.hasNext());
        return result;
    }

    /**
     * Specialization of {@link #getLast(Collection)} for lists, using
     * get(size-1).
     */
    public static Object getLast(List c) {
        return c.get(c.size() - 1);
    }
}

Related

  1. getLastElement(Collection collection, T defaultValue)
  2. getLastElement(final Collection collection)
  3. getLastOfCollection(Collection collection)
  4. getLastOrNull(Collection collection)