This post will discuss how to check if a value exists in an array in Java. The solution should return true if the array contains the given element; false otherwise.

1. Using an intermediate List

You can use Arrays.asList() to get a list backed by the array and call the List::contains method to determine if a value is present in the list or not.

Download  Run Code

 
The above solution doesn’t work for arrays of primitives. If you prefer the Guava library, use the Ints.asList() method for primitives.

Download Code

2. Using an intermediate Set

Alternatively, you can construct a set from the array elements and call the Set::contains method to determine whether the given value is present in it. This is demonstrated below for a String array.

Download  Run Code

 
Here’s an example for primitive arrays using Java 8 Stream:

Download  Run Code

3. Using Apache Commons Lang Library

One can also leverage the ArrayUtils.contains() method offered by Apache Commons Lang library, which returns true if the array contains the specified value. It is overloaded for all primitives types and object arrays.

Download Code

4. Using Stream.anyMatch() method

With Java 8 and above, you can create a stream and check if any elements of the stream match with the given element using the anyMatch() method. This is demonstrated below for a String array:

Download  Run Code

 
For primitive arrays, use the == operator to match with the given element.

Download  Run Code

5. Using Stream.filter() method

Another approach is to convert the given array into the stream and filter all occurrences of the specified element using the filter() method. Then, call the findFirst() method that returns an Optional.

Download  Run Code

 
You can also call the count() method to get the count of the specified element in the array:

Download  Run Code

 
For primitive arrays, use the == operator for comparison.

Download  Run Code

That’s all about checking if a value exists in an array in Java.