Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 556
tom Avatar asked Dec 02 '11 18:12

tom


People also ask

How do I get the last element in a collection?

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.

How do you find the last element of an ArrayList?

Approach: Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.

How can I get the last element of a stream?

Getting the Last Element of an Infinite StreamStream<Integer> stream = Stream. iterate(0, i -> i + 1); stream. reduce((first, second) -> second). orElse(null);

How do I see the last element in a stack?

lastElement() method in Java is used to retrieve or fetch the last element of the Stack. It returns the element present at the last index of the Stack. Parameters: The method does not take any parameter. Return Value: The method returns the last element present in the Stack.


1 Answers

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; } 
like image 167
Jack Edmonds Avatar answered Sep 20 '22 03:09

Jack Edmonds