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.
java - How to get the last value of an ArrayList - Stack Overflow
How to get the last value of an element in a List in Java? - Stack Overflow
How to get the last element of list in tcl?
The easy way to access the last JavaScript array element
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 prior to Java 21.
Google Guava
The Google Guava library is great - check out their Iterables.getLast() method. 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);