Java List indexOf method

There is a very important method indexOf which is part of the List interface. The description in Java documentation states:

“Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.”

Example:

import java.util.Arrays;
import java.util.List;

public class MainListIndexOfTest {
    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 2, 4, 5);

        System.out.println(list);
        int index = list.indexOf(2);
        // It will print index 1, although there is second occurrence of '2'
        System.out.println("First index of '2' is: " + index);

        // There is also the opposite connection with get method.
        // it will return the object on a certain index in the List
        Integer elementFromList = list.get(index);
        System.out.println("Element from the list: " + elementFromList);

        // In case when we have array we can create List and use it again
        String[] arr = new String[] {"A", "B", "C", "D"};

        List<String> list1FromArr = Arrays.asList(arr);
        int indexOfC = list1FromArr.indexOf("C");
        System.out.println("Index of 'C' is: " + indexOfC);
    }
}

Output:

[1, 2, 3, 2, 4, 5]
First index of '2' is: 1
Element from the list: 2
Index of 'C' is: 2

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.