Skip to content

Check if array contains value Java example

Check if array contains value Java example shows how to check if array contains a value in Java using various approaches.

How to check if an array contains a value in Java?

Let’s first create an array as given below. We are going to use a string array for our example.

There are several ways using which we can check if the above array contains a specific value as given below.

1) Using for loop

The simplest way to search an element in an array is to loop through the array and compare the value like given below.

Output

The contains method defined above uses generics and can be used with any object type. However, it does not work with the primitive array. In the case of primitive value, use a specific implementation of the contains method.

2) Using the asList and contains methods of List

We can convert array to List object using the asList method and then use the contains method of the List to search value in array as given below.

Output

Note: This approach does not work with an array of primitives.

3) Using the sort and binarySearch methods of the Arrays class

Above given approaches are useful if you want to do a few searches in an array. If the requirement is to search value in an array again and again, it is better to sort the array once and then use the binary search multiple times to check if the array contains given values.

This approach performs better when we want to search value in the same array lot many times.

4) Using the Apache Commons

If you are using the Apache Commons library, you can use the contains method of the ArrayUtils class to search elements in an array as given below.

Output

5) Using Java 8 Stream

If you are using version Java 8, you can use the Stream to search elements in an array as given below.

Output

6) Using the HashSet class

The HashSet class provides constant-time performance for contains operation. You can convert an array to HashSet and then use its contains method to search an element in the array as given below.

Output

Since the HashSet provides constant-time performance for contains operation, this approach gives better performance if you want to search the same array many times.

This example is a part of the Java String tutorial with examples and the Java Array tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.