How to get first and last element of ArrayList in java

Most of the times, we encountered the situation to read the first element of ArrayList using get(0) method. Some instances, you want to get the last element of an array List,. This post talks about multiple ways to read last element of an ArrayList or LinkedList.

For example, Let’s create an array list for this example

ArrayList<String> list=new ArrayList<>();  

Java List provides size() method to return number of elements.

First element can be accessed using index=0 Last element can be accessed using size-1.

How to get First object of List in java?

It returns first element using get method with index=0


How to get Last Element of List in java?

(size-1) return the last index of the list.


This returns last element from an array list.

In runtime, if there are no elements in the list,calling list.get(list.size()-1) throws java.lang.IndexOutOfBoundsException.

To avoid it, Please add check for checking list is not empty or null Here is the code snippet
Example program

String lastElement=list.get(list.size()-1);  

Java8 lambda expression to get first Last element of ArrayList 

Lamda expression are introduced in java8 to simplify list manipulation and introducing functional programming Function.

String last=list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1));
String first=list.isEmpty() ? Optional.empty() : Optional.of(list.get(0));

The java8 provides latest features.Please click here .

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.