To find the index of a specified element in a list in Java, you can use the indexOf
method of the List interface.
In this example,
myList
with some elements using the Arrays.asList
method.indexOf
method of the list object myList
to find the index of a specific element.indexOf
method returns the index of the first occurrence of the element in the list, or -1 if the element is not found.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> myList = Arrays.asList(10, 20, 30, 40, 50);
int index = myList.indexOf(40);
System.out.println("Index of element is: " + index);
}
}
Index of element is: 3
In this example,
myList
with some string elements using the Arrays.asList
method.indexOf
method of the list object myList
to find the index of a specific string.indexOf
method returns the index of the first occurrence of the string in the list, or -1 if the string is not found.import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> myList = Arrays.asList("apple", "banana", "cherry", "date", "elderberry");
int index = myList.indexOf("cherry");
System.out.println("Index of element is: " + index);
}
}
Index of element is: 2
In this tutorial, we learned How to get the Index of Specified Element in a List in Java language with well detailed examples.