Java get last element of a collection

前端 未结 10 788
你的背包
你的背包 2020-12-30 18:47

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

One solution is to first toArray(), and

相关标签:
10条回答
  • 2020-12-30 19:13

    To avoid some of the problems mentioned above (not robust for nulls etc etc), to get first and last element in a list an approach could be

    import java.util.List;
    
    public static final <A> A getLastElement(List<A> list) {
        return list != null ? getElement(list, list.size() - 1) : null;
    }
    
    public static final <A> A getFirstElement(List<A> list) {
        return list != null ? getElement(list, 0) : null;
    }   
    
    private static final <A> A getElement(List<A> list, int pointer) {
        A res = null;
        if (list.size() > 0) {
            res = list.get(pointer);            
        }
        return res;
    }
    

    The convention adopted is that the first/last element of an empty list is null...

    0 讨论(0)
  • 2020-12-30 19:16

    There isn't a last() or first() method in a Collection interface. For getting the last method, you can either do get(size() - 1) on a List or reverse the List and do get(0). I don't see a need to have last() method in any Collection API unless you are dealing with Stacks or Queues

    0 讨论(0)
  • 2020-12-30 19:17

    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;
    }
    
    0 讨论(0)
  • 2020-12-30 19:20

    Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too.

    0 讨论(0)
提交回复
热议问题