Java Basic Examples

Check if array contains value Java example

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

How to check if array contains value in Java?

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

There are several ways using which you can check if array contains value as given below.

1) Check if array contains value 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

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

2) Check if array contains value using asList and contains methods of List

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

Output

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

3) Check if array contains value using sort and binarySearch methods of 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 binary search multiple times to check if array contains given values.

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

4) Check if array contains value using Apache Commons

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

Output

5) Check if array contains value using Java 8 Stream

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

Output

6) Check if array contains value using HashSet

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

Output

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

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

 

Join 1000+ fellow learners! Enter your email address below: