Find the index of an element in an array in Java

In this post, we will see how to find the index of an element in a primitive or object array in Java.

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


 

1. Naive: Linear search

Naive solution would be to perform a linear search on the given array to determine if target element if present in the array or not.

 

1.1. For primitive arrays

 

1.2. For Object arrays

 

2. Java 8: Stream

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

 

2.1. For primitive arrays

 

2.2. For Object arrays

 

3. Convert To List

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

 

4.1. For primitive arrays

How to convert int array to List<Integer>?

 

4.2. For Object arrays

How to convert an Object array to a List?

 

4. Binary search for Sorted Arrays

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

 

4.1. For primitive arrays

 

4.2. For Object arrays

 

5. Guava

 

5.1. For primitive arrays

Guava library provides several utility class 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 indexOf() method that returns the index of the first appearance of the target in array. We can also use lastIndexOf() to returns the index of the last appearance of the target in array.

 

5.2. For Object arrays

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

 
We can also use 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. Apache Commons Lang

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

 

6.1. For primitive arrays

 

6.2. For Object arrays

 
 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding:)
 





Leave a Reply

Notify of
avatar
wpDiscuz