Get the Last Element from an ArrayList in Java

  1. Get Last Element Using the size() and get() Methods
  2. Convert ArrayList into LinkedList in Java
  3. Convert ArrayList into ArrayDeque in Java
  4. Using the Guava Library
  5. Summary

This tutorial introduces how to get last element from an ArrayList in Java, and also lists some example codes to understand the topic.

An ArrayList is a dynamic array that can be used to store similar data in an ordered collection. A great thing about Arrays and ArrayList is that they allow random access to any element stored in them, given that we know the index where it is stored. But how can we access the last element of an ArrayList if we don’t know its index? Some other languages like Python provide reverse indexing so we can use -1 to access the last element. In this tutorial, we will learn how to get the last element from an ArrayList in Java.

Get Last Element Using the size() and get() Methods

An ArrayList in Java has the size() method that can be used to find the number of elements present in the ArrayList.

import java.util.ArrayList;
public class LastElement
{
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);
		System.out.printf("The list contains %d elements", list.size());
	}
}

Output:

The list contains 5 elements

We know that the last index of an ArrayList will be one less than its length(because it follows zero-based indexing). We can use this information to fetch the last element. We will use the get() method of ArrayList to get the last element.

import java.util.ArrayList;
public class LastElement
{
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);
		int lastIdx = list.size() - 1;
		int lastElement = list.get(lastIdx);
		System.out.println("The last index of list is: " + lastIdx);
		System.out.print("The last element of list is: " + lastElement);
	}
}

Output:

The last index of list is: 4The last element of list is: 25

Let’s write a Generic method to avoid writing the same logic again and again.

import java.util.ArrayList;
public class LastElement
{
	public static <E> E getLastElement(ArrayList<E> list)
	{
		int lastIdx = list.size() - 1;
		E lastElement = list.get(lastIdx);
		return lastElement;
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list1 = new ArrayList<Integer>();
		list1.add(5);
		list1.add(10);
		list1.add(15);
		list1.add(20);
		list1.add(25);		
		ArrayList<String> list2 = new ArrayList<String>();
		list2.add("1");
		list2.add("2");
		list2.add("3");		
		System.out.println("The last element of list1 is: " + getLastElement(list1));
		System.out.print("The last element of list2 is: " + getLastElement(list2));
	}
}

Output:

The last element of list1 is: 25
The last element of list2 is: 3

What will happen if we run our method on an empty ArrayList? We will get an IndexOutOfBoundsException if we run the above code on an empty list. This happens because the size() method returns zero for an empty ArrayList and when we subtract 1 from it we get -1 as the index. There is no such thing as a negative index. The following example will return this exception.

import java.util.ArrayList;
public class LastElement
{
	public static <E> E getLastElement(ArrayList<E> list)
	{
		int lastIdx = list.size() - 1;
		E lastElement = list.get(lastIdx);
		return lastElement;
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list1 = new ArrayList<Integer>();
		System.out.println("The last element of list1 is: " + getLastElement(list1));
	}
}

Let’s check for a few conditions before running the size() method. We will use the isEmpty() method to check if the list is empty.

import java.util.ArrayList;
public class LastElement
{
	public static <E> E getLastElement(ArrayList<E> list)
	{
		if((list != null) && (list.isEmpty() == false))
		{
			int lastIdx = list.size() - 1;
			E lastElement = list.get(lastIdx);
			return lastElement;
		}
		else
			return null;
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		System.out.println("The last element of list is: " + getLastElement(list));
	}
}

Output:

The last element of list is: null

Convert ArrayList into LinkedList in Java

The LinkedList class, just like ArrayList, implements the List interface. The LinkedList class has a simple getLast() method that can be used to fetch the last element of the list.

If we can convert our ArrayList into a LinkedList, then we can use this method. This process won’t modify our original ArrayList.

import java.util.ArrayList;
import java.util.LinkedList
public class LastElement
{
	public static <E> E getLastElementUsingLinkedList(ArrayList<E> arrList)
	{
		LinkedList<E> linkedList = new LinkedList<E>(arrList);
		return linkedList.getLast();
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);
		System.out.println("The last element of list is: " + getLastElementUsingLinkedList(list));
		System.out.print("The array list is: " + list );
	}
}

Output:

The last element of list is: 25
The array list is: [5, 10, 15, 20, 25]

The above solution is not an elegant way of getting the last element and it is not recommended. If we need to access the last element multiple times then it is recommended to use LinkedList (or some other collection) instead of ArrayList.

Convert ArrayList into ArrayDeque in Java

A deque is a double-ended queue. An ArrayDeque combines the resizable array functionalities with the deque data structure. Just like LinkedList, the ArrayDeque also has a convenient getLast() method that can be used to view the last element of the deque. We simply need to convert our ArrayList to an ArrayDeque to make use of this method.

import java.util.ArrayDeque;
import java.util.ArrayList;
public class LastElement
{
	public static <E> Object getLastElementUsingArrayDeque(ArrayList<E> arrList)
	{
		ArrayDeque<E> deque = new ArrayDeque<E>(arrList);
		return deque.getLast();
	}
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);	
		System.out.println("The last element of list is: " + getLastElementUsingArrayDeque(list));
		System.out.print("The array list is: " + list );
	}
}

Again, this method is not very elegant and if we need to access the last element multiple times then it is suggested to use ArrayDeque instead of an ArrayList.

Using the Guava Library

The Google Guava library provides an easy method to get the last element from an ArrayList. We will use the getLast() method of the Iterables class of this library to get the last element. Make sure to download and add this library to your project before running the following code.

import java.util.ArrayList;
import com.google.common.collect.Iterables;
public class LastElement
{
	public static void main(String[] args)
	{
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(5);
		list.add(10);
		list.add(15);
		list.add(20);
		list.add(25);		
		Integer lastEle = Iterables.getLast(list);
		System.out.print("The last element of the array list is: " + lastEle);
	}
}

Output:

The last element of the array list is: 25

We can also provide a default value to the getLast() method to display if the list is empty. This will prevent Java from throwing any exceptions.

import java.util.ArrayList;
import com.google.common.collect.Iterables;
public class LastElement
{
	public static void main(String[] args)
	{
		ArrayList<String> list = new ArrayList<String>();
		String lastEle = Iterables.getLast(list, "No Element Found");//No Element Found is the             															   default value
		System.out.print("The last element of the array list is: " + lastEle);
	}
}

Output:

The last element of the array list is: No Element Found

Summary

An ArrayList is a very common data structure that is mostly used to eliminate the issue of normal arrays on limited size. We may not know the last index of the list in many cases, so we can’t find the last element stored in it.

We can use the size() and get() methods to view this element. The Google Guava library also provides an easy way of fetching the last element.

If we frequently need to access the last element, it is preferred to use some other collection like LinkedList or ArrayDeque as these collections have the required methods.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java ArrayList

  • Get ArrayList of int array in Java
  • Convert Int Array to Arraylist in Java