Explain Codes LogoExplain Codes Logo

How to get the last value of an ArrayList

java
null-safety
best-practices
time-complexity
Nikita BarsukovbyNikita Barsukov·Nov 3, 2024
TLDR

Get the last element of an ArrayList using .get(list.size() - 1):

ArrayList<String> list = new ArrayList<>(Arrays.asList("First", "Second", "Third")); // Yoink! Grabbing the last item here. String last = list.get(list.size() - 1);

In this instance, last would be "Third", the last item in our ArrayList.

Safe guards: Null and empty check

Checking if the list is empty or null is pivotal to prevent us from that heart-attack inducing IndexOutOfBoundsException or NullPointerException.

Check for empty ArrayList

Ask your list politely if it's empty before trying to get anything from it:

if (!list.isEmpty()) { // "Pretty please, List, can I have your last item?" E lastElement = list.get(list.size() - 1); } else { // "Oh, you're empty. Nevermind then." // Handle the case when the list is empty }

Handling null ArrayLists

Don't presume the list exists! Check first, or face the null's wrath:

if (list != null && !list.isEmpty()) { // "List, I heard from my crystal ball you're not empty." E lastElement = list.get(list.size() - 1); }

Leveraging Guava for grace and simplicity

Are you a fan of Guava, Google's core Java libraries? There's an elegant way to get the last element without headaches:

// As Bob Ross says: "There are no mistakes, just happy accidents." E lastElementOrDefault = Iterables.getLast(list, defaultValue); // Here's an enchilada (Optional) of the last element. Optional<E> lastElement = Optional.ofNullable(Iterables.getLast(list, null));

Using Optional helps communicate your intentions more clearly and provides null safety, while Iterables.getLast() simplifies your code, making it more readable.

Efficiency for large lists: Time complexity

For large lists, time complexity matters just like real estate — it's all about location! Luckily, list.get(list.size() - 1) is a constant time operation, not slowing down as the list grows.

Default values: Plan B for empty lists

Sometimes, a Plan B is helpful. Here's how to set default values for potentially empty lists:

Default values with Java Collections

// A default value, because an empty list doesn't mean the world ends. E lastElement = list.isEmpty() ? defaultValue : list.get(list.size() - 1);

Default values with Guava's Lists

Here's the Guava way of handing out a consolation prize when the list is empty:

// Under every empty list, there's a consolation prize! E lastElement = Lists.getLast(list, defaultValue);

Guava's Lists: Added functionality

Guava's Lists hides additional surprises, such as getFirst(). Remember to keep a sharp eye on your time complexity requirements when using these methods.

Intentional code: Best practices

Choose methods consciously based on your specific needs. In most scenarios, list.get(list.size() - 1) offers a perfect balance of being direct and efficient, unless you're deep into Guava, making use of its additional benefits.