Java ArrayList lastIndexOf() Method Example

ArrayList Methods with Examples


Java ArrayList Examples


The java.util.ArrayList.lastIndexOf(Object) method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

Java ArrayList lastIndexOf() Method Example

The following example shows the usage of java.util.ArrayList.lastIndexOf() method:

import java.util.ArrayList;
import java.util.List;

// Check if an ArrayList contains a given element | contains()

// Find the index of the first occurrence of an element in an ArrayList | indexOf()

// Find the index of the last occurrence of an element in an ArrayList | lastIndexOf()

public class SearchElementsInArrayListExample {
    public static void main(String[] args) {
         // Creating an ArrayList of String using
        List<String> fruits = new ArrayList<>();
        // Adding new elements to the ArrayList
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("mango");
        fruits.add("orange");
        fruits.add("Watermelon");
        fruits.add("Strawberry");
     
        // Check if an ArrayList contains a given element
        System.out.println("Does names array contain \"mango\"? : " + fruits.contains("mango"));

        // Find the index of the last occurrence of an element in an ArrayList
        System.out.println("lastIndexOf \"Watermelon\" : " + fruits.lastIndexOf("Watermelon"));
        System.out.println("lastIndexOf \"Strawberry\" : " + fruits.lastIndexOf("Strawberry"));
    }
}
Output:
lastIndexOf "Watermelon" : 4
lastIndexOf "Strawberry" : 5

Reference


Comments