The syntax of the lastIndexOf()
method is:
arraylist.lastIndexOf(Object obj)
Here, arraylist is an object of the ArrayList
class.
lastIndexOf() Parameter
The lastIndexOf()
method takes a single parameter.
- obj - element whose position is to be returned
If the same element obj is present in multiple locations, then the position of the element that appears last is returned.
lastIndexOf() Return Value
- returns the position of the last occurrence of the specified element from the arraylist
Note: If the specified element doesn't exist in the list, the lastIndexOf()
method returns -1.
Example: Get the Last Occurrence of ArrayList Element
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList<String> languages = new ArrayList<>();
// insert element to the ArrayList
languages.add("JavaScript");
languages.add("Python");
languages.add("Java");
languages.add("C++");
languages.add("Java");
System.out.println("Programming Languages: " + languages);
// get the position of Java occurred last
int position1 = languages.lastIndexOf("Java");
System.out.println("Last Occurrence of Java: " + position1);
// C is not in the ArrayList
// Returns -1
int position2 = languages.lastIndexOf("C");
System.out.println("Last Occurrence of C: " + position2);
}
}
Output
Programming Languages: [JavaScript, Python, Java, C++, Java] Last Occurrence of Java: 4 Last Occurrence of C: -1
In the above example, we have created an arraylist named languages. Notice the expressions,
// returns 4
languages.lastIndexOf("Java")
// returns -1
languages.lastIndexOf("C")
Here, the lastIndexOf()
method successfully returns the position of the last occurrence of Java (i.e. 4). However, element C doesn't exist in the arraylist. Hence, the method returns -1.
And, if we want to get the first occurrence of Java, we can use the indexOf()
method. To learn more, visit Java ArrayList indexOf().
Note: We can also get the element present in a particular location using the Java ArrayList get() method.