Java List indexOf: Find Element Index

To find the index position of a certain element in a List, you can use the indexOf() method. This method takes one parameter, the element to be searched for, and returns the index position of the first occurrence of that element in the List. If the element does not exist in the List, it will return -1.

An example is shown as follows:

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

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");

        int index = list.indexOf("B");
        System.out.println("Index of 'B': " + index);
    }
}

In the above code, a List containing elements “A”, “B”, and “C” is created first. Then the indexOf() method is used to get the index position of the element “B” in the List, and the result is printed out.

bannerAds