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.
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; }
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; }
Note that the output of the binary search algorithm can’t be predicted for an unsorted array.
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); }
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); }
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); }
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.