Java Arraylist.lastIndexOf()

Learn how to get the index of the last occurrence of an element in ArrayList using the ArrayList.lastIndexOf() method. To get the index of the first occurrence, use the indexOf() method.

1. ArrayList.lastIndexOf() API

The lastIndexOf(e) returns the index of the last occurrence of the specified element ‘e’ in this list. It will return '-1' if the list does not contain the element.

public int lastIndexOf(Object object)

The lastIndexOf() takes only a single argument object which needs to be searched in the list for its last index position.

The lastIndexOf() returns:

  • index – last index position of the element if the element is found.
  • -1 – if the element is NOT found.

2. ArrayList lastIndexOf() Example

The following Java program gets the last index of arraylist. In this example, we are looking for last occurrence of strings “alex” and “hello“.

  • The String ‘alex‘ occurs thrice in the list, the second occurrence is at index position 6.
  • The string ‘hello‘ is not present in the list.

Please note that arraylist indices start from 0.

ArrayList<String> list = new ArrayList<>(Arrays.asList("alex", "brian", "charles","alex","dough","gary","alex","harry"));

int lastIndex = list.lastIndexOf("alex");


lastIndex = list.lastIndexOf("hello");


Program output.


Happy Learning !!

Read More: ArrayList Java Docs


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode