Java get last element of a collection

JavaCollectionsIterator

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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;
}

Solution 2 - Java

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

Solution 3 - Java

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;
}

Solution 4 - Java

This should work without converting to List/Array:

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

Solution 5 - Java

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)

Solution 6 - Java

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();
}

Solution 7 - Java

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

Solution 8 - Java

Or you can use a for-each loop:

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

Solution 9 - Java

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontomView Question on Stackoverflow
Solution 1 - JavaJack EdmondsView Answer on Stackoverflow
Solution 2 - JavapalacsintView Answer on Stackoverflow
Solution 3 - Javanikolai.serdiukView Answer on Stackoverflow
Solution 4 - JavaSamad CharaniaView Answer on Stackoverflow
Solution 5 - JavakukudasView Answer on Stackoverflow
Solution 6 - JavaNick GarveyView Answer on Stackoverflow
Solution 7 - JavaPiyush MattooView Answer on Stackoverflow
Solution 8 - JavaassyliasView Answer on Stackoverflow
Solution 9 - JavaravthiruView Answer on Stackoverflow