Find the Last Position of an ArrayList in Java

The lastIndexOf(Object obj) returns the position of the last occurrence of an element in an ArrayList.

public int lastIndexOf(Object obj): This method returns the index of the last occurrence of the object obj in the ArrayList. If the object doesn't exist, it returns -1.

In this example, we have an ArrayList of strings that contains a few duplicate elements. We look for the last index of a few elements using the method lastIndexOf().

import java.util.ArrayList; 

public class ArrayListLastIndexOf{

public static void main(String[] args) {

// Create an ArrayList< String>
ArrayList< String> arraylist = new ArrayList< String> ();

//add strings to ArrayList
arraylist.add("obj1");
arraylist.add("obj3");
arraylist.add("obj5");
arraylist.add("obj2");
arraylist.add("obj1");
arraylist.add("obj3");
arraylist.add("obj1");
arraylist.add("obj3");

System.out.println("last occurrence of obj1: "+arraylist.lastIndexOf("obj1"));
System.out.println("last occurrence of obj3: "+arraylist.lastIndexOf("obj3"));
}
}
Runtime:

last occurrence of obj1:6
last occurrence of obj3:7