[java] Java get last element of a collection

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 then return the last element of the array. Is there any other better ones?

This question is related to java collections iterator

The answer is


Or you can use a for-each loop:

Collection<X> items = ...;
X last = null;
for (X x : items) last = x;

A reasonable solution would be to use an iterator if you don't know anything about the underlying Collection, but do know that there is a "last" element. This isn't always the case, not all Collections are ordered.

Object lastElement = null;

for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); ) {
  lastElement = collectionItr.next();
}

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


Well one solution could be:

list.get(list.size()-1)

Edit: You have to convert the collection to a list before maybe like this: new ArrayList(coll)


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...


If you have Iterable convert to stream and find last element

 Iterator<String> sourceIterator = Arrays.asList("one", "two", "three").iterator();

 Iterable<String> iterable = () -> sourceIterator;


 String last = StreamSupport.stream(iterable.spliterator(), false).reduce((first, second) -> second).orElse(null);

This should work without converting to List/Array:

collectionName.stream().reduce((prev, next) -> next).orElse(null)

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


A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement = itr.next();
    }
    return lastElement;
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to iterator

Iterating over Typescript Map Update row values where certain condition is met in pandas How to iterate (keys, values) in JavaScript? How to convert an iterator to a stream? How to iterate through a list of objects in C++ How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it? How to read one single line of csv data in Python? 'numpy.float64' object is not iterable Python list iterator behavior and next(iterator) python JSON only get keys in first level