English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Oriented Object (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java ArrayList lastIndexOf() usage and example

Java ArrayList Methods

The Java ArrayList lastIndexOf() method returns the last occurrence position of the specified element.

The syntax of lastIndexOf() method is:

arraylist.lastIndexOf(Object obj)

lastIndexOf() parameter

  • obj - The element to return the position of

If the same element obj appears at multiple positions, the position of the last occurrence of the element will be returned.

lastIndexOf() return value

  • Return the last occurrence position of the specified element from the ArrayList

NoteIf the specified element does not exist in the list, the lastIndexOf() method returns -1.

Example: Get the last occurrence position of an element in ArrayList

import java.util.ArrayList;
class Main {
    public static void main(String[] args) {
        //Create an ArrayList
        ArrayList<String> languages = new ArrayList<>();
        //Add elements to the ArrayList
        languages.add("JavaScript");
        languages.add("Python");
        languages.add("Java");
        languages.add("C",++");
        languages.add("Java");
        System.out.println("Programming language: ", + languages);
        //Last occurrence position
        int position1 = languages.lastIndexOf("Java");
        System.out.println("The last occurrence of Java: ", + position1);
                //C is not in the ArrayList
                //Returns-1
        int position2 = languages.lastIndexOf("C");
        System.out.println("The last occurrence of C: ", + position2);
    }
}

Output Result

Programming Languages: [JavaScript, Python, Java, C++, Java]
The last occurrence of Java: 4
The last occurrence of C: -1

In the above example, we created an array list named languages. Note these expressions,

// Returns 4
languages.lastIndexOf("Java")
// Returns -1
languages.lastIndexOf("C")

Here, the lastIndexOf() method successfully returnedJavaThe last occurrence position (i.e.,4)。However, the elementCIt does not exist in the arraylist. Therefore, this method returns-1.

And, if we want to find the first occurrence of Java, we can use the indexOf() method. For more information, please visitJava ArrayList indexOf().

NoteWe can also useJava ArrayList get()Method to get the element at the specified position.

Java ArrayList Methods