java – How to get the last value of an ArrayList

java – How to get the last value of an ArrayList

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 isnt 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 youre using Options:

lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);

java – How to get the last value of an ArrayList

this should do it:

if (arrayList != null && !arrayList.isEmpty()) {
  T item = arrayList.get(arrayList.size()-1);
}

Leave a Reply

Your email address will not be published.