javacollections

Get the last element of a Java collection


I have a collection, and I want to get the last element of it. What's the most straighforward and fast way to do so?

One solution is to first toArray(), and then return the last element of the array. Are there any other better ones?


Solution

  • It is not very efficient solution, but working one:

    public static <T> T getFirstElement(final Iterable<T> elements) {
        return elements.iterator().next();
    }
    
    public static <T> T getLastElement(final Iterable<T> elements) {
        T lastElement = null;
    
        for (T element : elements) {
            lastElement = element;
        }
    
        return lastElement;
    }