Tuesday, November 22, 2011

Find last Element/Object of ArrayList in java

get the Last Element of List 

Most of the times we encountered the situation to read the first element of ArrayList using get(0) method. Some instances you want to read the last element of an array List, you can use the following code snippet.
ArrayList list=new ArrayList();

To Access the fourth object, we have to use list.get(list.size()-1). Here size() method returns the size of the list and size -1 return the last index of the list.
Example program
In runtime if there are no elements in the list,if you call method list.get(list.size()-1), it will throw IndexOutOfBoundsException. always make sure that you call this method if the list is not empty or null check.
Here is the code snippet
String lastElement=(String) list.get(list.size()-1);

Lamda expression to get Last element of ArrayList 

Lamda expression are introduced in java8 to simplify it and introducing functional programming Function
Function<ArrayList<String>, String> getLast = a -> a.get(a.size() - 1);

The function is an interface with the single abstract method. Please click here for more about Functions With this, the number of lines code reduced.

Related article