Java get last element of a collection
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;
}
Iterables.getLast
from Google Guava.
It has some optimization for List
s and SortedSet
s too.
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
/NavigableSet
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
/NavigableSet
. 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;
}