How to get the 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 the List in java?

It returns the first element using the 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 the 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 Functions.

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 .