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.

Download  Run Code

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.

Download  Run Code

3. Using for loop

Here’s an equivalent version without using the Stream API.

Download  Run Code

That’s all about finding the index of an element in a List in Java.