Java Collection Last getLastElement(final Collection collection)

Here you can find the source of getLastElement(final Collection collection)

Description

get Last Element

License

Apache License

Declaration

public static <T> T getLastElement(final Collection<T> collection) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Collection;

import java.util.List;

public class Main {
    public static <T> T getLastElement(final Collection<T> collection) {

        if (isEmpty(collection)) {
            return null;
        }//from www . j  a  v a 2s .  co m
        if (collection instanceof List) {
            List<T> list = (List<T>) collection;
            return list.get(list.size() - 1);
        } else {
            T last = null;
            for (T next : collection) {
                last = next;
            }
            return last;
        }
    }

    /**
     * Returns true if the collection is null or empty; false otherwise.
     * 
     * @param collection
     *            the collection to be tested.
     * @return true if the collection is null or empty; false otherwise.
     */
    public static boolean isEmpty(final Collection<?> collection) {

        return collection == null || collection.isEmpty();
    }
}

Related

  1. getLast(Collection c)
  2. getLastElement(Collection collection, T defaultValue)
  3. getLastOfCollection(Collection collection)
  4. getLastOrNull(Collection collection)
  5. implodeCollection(Collection items, String prefix, String suffix, String delimiter, String lastItemSuffix)
  6. lastIndexOfObjectIdentity(Collection collection, Object object)