How can I get the last value of an ArrayList?
I don't know the last index of the 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.
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.
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.
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.
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.
There isn't an elegant way in vanilla Java.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With