This post will discuss how to find the index of an element in a primitive or object array in Java.

The solution should either return the index of the first occurrence of the required element or -1 if it is not present in the array.

1. Naive Solution – Linear search

A naive solution is to perform a linear search on the given array to determine whether the target element is present in the array.

⮚ For primitive arrays:

⮚ For object arrays:

2. Using Java 8 Stream

We can use Java 8 Stream to find the index of an element in a primitive and object array, as shown below:

⮚ For primitive arrays:

⮚ For object arrays:

3. Convert To List

The idea is to convert the given array to a list and use the List.indexOf() method that returns the index of the first occurrence of the specified element in this list.

⮚ For primitive arrays:

How to convert primitive integer array to List<Integer>?

⮚ For object arrays:

How to convert an object array to a list?

For sorted arrays, we can use Binary Search Algorithm to search the specified array for the specified value.

⮚ For primitive arrays:

⮚ For object arrays:

5. Using Guava Library

⮚ For primitive arrays:

Guava library provides several utility classes pertaining to primitives, like Ints for int, Longs for long, Doubles for double, Floats for float, Booleans for boolean, and so on.

Each utility class has the indexOf() method that returns the index of the first appearance of the target in the array. We can also use lastIndexOf() to return the index of the target’s last appearance in the array.

⮚ For object arrays:

Guava’s com.google.commons.collect.Iterables class contains static utility method indexOf(Iterator, Predicate) that returns the index of the first element that satisfies the provided predicate, or -1 if the iterator has no such elements.

 
We can also use the com.google.common.base.Predicates class provided by Guava that contains static utility methods pertaining to Predicate instances.

 
For Java 8 and above, we can use lambda expressions:

6. Using Apache Commons Lang

Apache Commons Lang ArrayUtils class contains several static utility methods that operate on primitive or object arrays. It provides the indexOf() method that finds the index of the given value in the array.

⮚ For primitive arrays:

⮚ For object arrays:

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