Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last value of an ArrayList

Tags:

java

arraylist

How can I get the last value of an ArrayList?

I don't know the last index of the ArrayList.

like image 232
Jessy Avatar asked Mar 26 '09 22:03

Jessy


People also ask

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 do I get the last element in a list?

Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want last element in list, use -1 as index.

What is the last index of an ArrayList?

The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter.

How do I find the first element of an ArrayList?

To get the first element of a ArrayList, we can use the list. get() method by passing 0 as an argument. 0 is refers to first element index.


2 Answers

The following is part of the List interface (which ArrayList implements):

E e = list.get(list.size() - 1); 

E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.

like image 62
Johannes Schaub - litb Avatar answered Sep 26 '22 06:09

Johannes Schaub - litb


There isn't an elegant way in vanilla Java.

Google Guava

The Google Guava library is great - check out their Iterables class. This method will throw a NoSuchElementException if the list is empty, as opposed to an IndexOutOfBoundsException, as with the typical size()-1 approach - I find a NoSuchElementException much nicer, or the ability to specify a default:

lastElement = Iterables.getLast(iterableList); 

You can also provide a default value if the list is empty, instead of an exception:

lastElement = Iterables.getLast(iterableList, null); 

or, if you're using Options:

lastElementRaw = Iterables.getLast(iterableList, null); lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw); 
like image 36
Antony Stubbs Avatar answered Sep 23 '22 06:09

Antony Stubbs