Find index of an element in List in Java
This post will discuss how to find the index of an element in a List in Java.
1. Using indexOf() method
The standard solution to find the index of an element in a List is using the indexOf() method. It returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.List; class Main { public static void main(String[] args) { List<Integer> values = List.of(5, 3, 4, 7, 6, 2, 9, 6); int item = 6; int index = values.indexOf(item); System.out.println(index); // 4 } } |
2. Using Stream API
With Stream API, you can do something like the following. The solution generates an IntStream of indices, and filter the indices containing the given element, and return the index of the first occurrence or -1 if no matching element is found.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.List; import java.util.Objects; import java.util.stream.IntStream; class Main { public static void main(String[] args) { List<Integer> values = List.of(5, 3, 4, 7, 6, 2, 9, 6); int item = 6; int index = IntStream.range(0, values.size()) .filter(i -> Objects.equals(values.get(i), item)) .findFirst() .orElse(-1); System.out.println(index); // 4 } } |
3. Using for loop
Here’s an equivalent version without using the Stream API.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.List; import java.util.Objects; class Main { public static void main(String[] args) { List<Integer> values = List.of(5, 3, 4, 7, 6, 2, 9, 6); int item = 6; int index = -1; for (int i = 0; i < values.size(); i++) { if (Objects.equals(values.get(i), item)) { index = i; break; } } System.out.println(index); // 4 } } |
That’s all about finding the index of an element in a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)