Check if an array contains specified value in Java

In this post, we will see how to check if a primitive or an object array contains specified value or not in Java.


1. Linear search

Naive solution would be to perform a linear search on the given array to check if specified value 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 check if an array contains specified value as shown below:


2.1. For primitive arrays

or, using filters:


2.2. For Object arrays

or, using filters:


3. Convert to Set or List

The idea is to wrap the given array in a List and use List.contains() that returns true if this list contains the specified element. We can also use Set in place of List.


3.1. For primitive arrays

Check how to convert primitive int array to a List?


3.2. For Object arrays


4. Binary Search Algorithm

For sorted arrays, we can use binary search to search the array for the specified value. Binary search algorithm returns the index of specified element if present in the array else it returns a negative value. We can determine if the array contains an element or not by simply checking if the computed index is greater or equal to zero.


4.1. For primitive arrays


4.2. For Object arrays


5. Apache Commons Lang

Apache commons Lang ArrayUtils class contains several static utility methods that operate on primitive or object arrays. It provides contains() method that checks if given value is present in the array or not.


5.1. For primitive arrays


5.2. For Object arrays


6. Guava


6.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 determine if the array contains an element or not by checking if the returned index is greater or equal to zero.


6.2. For Object arrays

Guava 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.

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

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