How to Check if Java Array Contains a Value?

There are many ways to check if a Java array contains a specific value.

  • Simple iteration using for loop
  • List contains() method
  • Stream anyMatch() method
  • Arrays binarySearch() for sorted array

Let’s look into all these methods one at a time.

1. Using For Loop

This is the easiest and convenient method to check if the array contains a certain value or not. We will go over the array elements using the for loop and use the equals() method to check if the array element is equal to the given value.

2. Using List contains() method

We can use Arrays class to get the list representation of the array. Then use the contains() method to check if the array contains the value. Let’s use JShell to run the example code snippet.

3. Using Stream anyMatch() Method

If you are using Java 8 or higher, you can create a stream from the array. Then use the anyMatch() method with a lambda expression to check if it contains a given value.

4. Arrays binarySearch() for sorted array

If your array is sorted, you can use the Arrays binarySearch() method to check if the array contains the given value or not.

Output:

Checking if Array Contains Multiple Values

What if we want to check if the array contains multiple values. Let’s say you want to check if a given array is the subset of the source array. We can create nested loops and check each element one by one. There is a cleaner way by converting arrays to list and then use the containsAll() method.

Output: vowels contains all the elements in subset = true

References

  1. Arrays binarySearch() API Doc
  2. Stream anyMatch() API Doc

By admin

Leave a Reply

%d bloggers like this: