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");
System.out.println(lastIndex);
lastIndex = list.lastIndexOf("hello");
System.out.println(lastIndex);
Program output.
6
-1
Happy Learning !!
Read More: ArrayList Java Docs