ArrayList
Programming
Java
Data Structures
Coding Tips

How to get the last value of an ArrayList

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In Java, an ArrayList is a resizable array implementation of the List interface. It provides a convenient way to store and manipulate a dynamic list of objects. One common operation with an ArrayList is retrieving the last element, which can be achieved in several ways depending on the context and specific requirements. In this article, we'll explore the methods to obtain the last value of an ArrayList, considering various scenarios and their implications for performance and readability.

Methods to Retrieve the Last Element of an ArrayList

Using Simple Indexing

The most straightforward method to access the last element of an ArrayList is by using its size to calculate the index of the last element. Since ArrayList provides the size() method, which returns the number of elements in the list, and since ArrayList is zero-based index, the last element is at position size() - 1.

Example:

java
1import java.util.ArrayList;
2
3public class Main {
4    public static void main(String[] args) {
5        ArrayList<String> list = new ArrayList<>();
6        list.add("Apple");
7        list.add("Banana");
8        list.add("Cherry");
9
10        String lastElement = list.get(list.size() - 1);
11        System.out.println("Last Element: " + lastElement);
12    }
13}

This will output Last Element: Cherry.

Using ListIterator

Another way to get the last element is using a ListIterator. This is particularly useful when you want to traverse the list in reverse order. The ListIterator can be obtained by calling the listIterator() method on the ArrayList.

Example:

java
1import java.util.ArrayList;
2import java.util.ListIterator;
3
4public class Main {
5    public static void main(String[] args) {
6        ArrayList<String> list = new ArrayList<>();
7        list.add("Apple");
8        list.add("Banana");
9        list.add("Cherry");
10
11        ListIterator<String> iterator = list.listIterator(list.size());
12        if (iterator.hasPrevious()) {
13            String lastElement = iterator.previous();
14            System.out.println("Last Element: " + lastElement);
15        }
16    }
17}

This method is useful if you need more control over the list traversal or if you start the iteration not knowing if you will need the last element or not.

Using Stream API (Java 8+)

For those using Java 8 and later, the Stream API provides a more modern approach to handling collections, including finding the last element.

Example:

java
1import java.util.ArrayList;
2import java.util.Optional;
3
4public class Main {
5    public static void main(String[] args) {
6        ArrayList<String> list = new ArrayList<>();
7        list.add("Apple");
8        list.add("Banana");
9        list.add("Cherry");
10
11        Optional<String> lastElement = list.stream().reduce((first, second) -> second);
12        lastElement.ifPresent(System.out::println); // Outputs "Cherry"
13    }
14}

The reduce() method combines the elements of the stream to a single value; in this case, it always passes the second argument as the accumulator, effectively returning the last element.

Considerations and Best Practices

  • Efficiency: The method of accessing via direct index (list.get(list.size() - 1)) is generally the most efficient, given its constant-time complexity (O(1)O(1)).
  • Safety: Always ensure the list is not empty to avoid IndexOutOfBoundsException. You can safeguard your code by checking if list.size() > 0 before accessing the last element.
  • Code Clarity: Choose the method that makes the code more readable and understandable within its context. For example, the Stream API might be preferred in an application that widely uses functional programming features.

Summary Table

MethodCode ClarityPerformanceUse Case
Direct IndexingHighExcellentWhen performance is crucial, and the list is not modified frequently.
ListIteratorMediumGoodUseful for reverse iteration or when index is unknown.
Stream APIHighModeratePreferred in functional programming or Java 8+ environments.

Conclusion

Retrieving the last element of an ArrayList can be done in multiple ways, each with its benefits and appropriate contexts. Understanding these methods allows Java developers to write more efficient, readable, and robust applications.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.