{

How to get first and last element of ArrayList in java


Most of the time, we encountered the situation to read the first element of ArrayList using the get(0) method.

In some instances, you want to get the last element of an Array List. This post talks about multiple ways to read the last element of an ArrayList or LinkedList.

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

ArrayList<String> list=new ArrayList<>();  
list.add("one");  
list.add("two");  
list.add("three");  
list.add("four");  

Java List provides size() method to return many elements.

The first element can be accessed using index=0 The last element can be accessed using size-1.

How to get the First object of List in java?

It returns first element using get method with index=0

  list.get(0);

How to get the Last Element of List in java?

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

  list.get(list.size()-1);

This returns the 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

if((list!=null)||(list.size()>0){  
String lastElement=list.get(list.size()-1);  
}  

Java8 lambda expression to get first Last element of ArrayList

Lambda expressions are introduced in java8 to simplify list manipulation and introduce 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 .

THE BEST NEWSLETTER ANYWHERE
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
Subscribe
You'll get a notification every time a post gets published here.