This post will discuss how to get the last value of a List in Java.

1. Using List.get() method

The size() method returns the total number of items present in the List. To retrieve the last element, you can use the expression L.get(L.size() - 1) where L is your list. Here’s the complete code:

Download  Run Code

 
This, however, throws an IndexOutOfBoundsException if the list is empty. To handle it, you can create a utility method with an additional size check on the list before calling its get() method.

Download  Run Code

2. Using Guava

With Google Guava, you can use the Iterables.getLast() method, designed specifically to get the last element of an iterable.

Download Code

 
This method will throw a java.util.NoSuchElementException if the iterable is empty. However, you can provide a default value in the second parameter to the Iterables.getLast() method to avoid the exception.

Download Code

3. Using Stream API

Here’s a solution using Stream API. The idea is to get a stream of all elements in the list, skip the first n-1 elements in it where n is the list’s size, and return the only element left in the stream.

This approach is demonstated below. It not recommended for Lists with RandomAccess support, as it takes linear time as opposed to O(1) time by above discussed methods.

Download  Run Code

4. Using for loop

A naive approach will be to use a for-loop to iterate through the array and return the last element. This approach is not recommended as it is very inefficient.

Download  Run Code

That’s all about getting the last value of a List in Java.