Core Java

Check If Java Array Contains a Given Value

Introduction:

In this quick tutorial, we’ll look at how to find if a Java array contains a given value. In other words, we’ll check if a given value is present in our Java array or not.

Linear Search:

One of the most straightforward approaches would be to linearly search our array to check if it contains the element we are looking for:

boolean checkIfElementExists(int[] a, int x) {
    for(int i=0; i < a.length; i++){
        if(a[i] == x)
            return true;
    }
    return false;
}

The idea here is to iterate through all the elements and look for the element x in our array.  This solution takes O(n) time.

Binary Search:

If we have a sorted array, we can use the Binary Search algorithm to check if the given element exists in our Java array:

boolean checkIfElementExists(int[] a, int x) {
    return Arrays.binarySearch(a, x) >= 0;
}

Here, we have used binarySearch() method from our java.util.Arrays class which always returns a non-negative value if the element exists in the given array.

Note that the output of the binary search algorithm can’t be predicted for an unsorted array.

java.util.List:

As we know, we have a contains() method in any List implementation. So one of the approaches we can adopt is to first convert our array to a List and then do a contains() check:

boolean checkIfElementExists(Integer[] a, int x) {
    List<Integer> list = Arrays.asList(a);
    return list.contains(x);
}

The java.util.Arrays.asList() method in Java converts an object array to a List.

java.util.Set:

Java Set implementations also support contains() method. That means we can also go about converting our array to a Set and later having a contains() check on our Set of elements. This approach will specifically be useful when we have a lot of duplicates in our array. Since duplicates won’t be added to our Set, the time required for our contains() check will drop off:

boolean checkIfElementExists(Integer[] a, int x) {
    List<Integer> list = Arrays.asList(a);
    Set<Integer> set = new HashSet<>(list);
    return set.contains(x);
}

To convert our array to a Set, we have first converted it to a List and later passed that list to the HashSet constructor.

Java 8 Streams:

When working on Java 8 or higher versions, we can quickly do the existence check using Java 8 Streams API:

boolean checkIfElementExists(int[] a, int x) {
    return Arrays.stream(a).anyMatch(item -> item == x);
}

To learn about Java 8 Streams API, check out this article.

Conclusion:

In this mini-article, we have looked at several ways in which we can do an existence check for an element in an array. The approach that we choose to opt for will vary from one use-case to another.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *