Determine whether a value is present in an array in Java
This post will discuss how to determine whether a value is present in an array in Java.
There are several ways to determine whether a value is present in an array. Some of the most common methods are:
1. Using Stream.filter() method
One way to check if an array contains a particular value is to use the Java 8 Stream API. The Stream API allows us to create a stream from an array and apply various operations on it, such as filtering, mapping, reducing, etc. The filter() method takes a predicate as an argument and returns a new stream that contains only the elements that satisfy the predicate. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.Arrays; class Main { // Method to check if a primitive array contains a particular value public static boolean isPresent(int[] a, int target) { // using filters return Arrays.stream(a) .filter(x -> x == target) .count() > 0; } // Generic method to check if an object array contains a particular object public static<T> boolean isPresent(T[] a, T target) { // using filters return Arrays.stream(a) .filter(target::equals) // or use `x -> target.equals(x)` .findAny().isPresent(); } public static void main(String[] args) { System.out.println(isPresent(new int[] { 10, 12, 14, 25, 16 }, 25)); // true System.out.println(isPresent(new String[] { "a", "b", "c" }, "e")); // false } } |
The above code above creates a stream from the array using the Arrays.stream() method, then applies the filter() method with a lambda expression that compares each element with the target value. Then, the findAny() method returns an optional that contains either one of the matching elements or an empty value if none is found. Finally, the isPresent() method checks if the optional has a value or not and returns a boolean.
2. Using Stream.anyMatch() method
We can also use the Stream.anyMatch() method instead of filter() and findAny(), which returns a boolean directly. We can use the Arrays.stream() method to create a stream from the array, and then use a lambda expression or method reference to specify the matching condition. This is a functional and elegant way of solving this problem. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Arrays; class Main { public static boolean isPresent(int[] a, int target) { return Arrays.stream(a) .anyMatch(x -> x == target); } public static<T> boolean isPresent(T[] a, T target) { return Arrays.stream(a) .anyMatch(target::equals); // or use `x -> target.equals(x)` } public static void main(String[] args) { System.out.println(isPresent(new int[] { 10, 12, 14, 25, 16 }, 25)); // true System.out.println(isPresent(new String[] { "a", "b", "c" }, "e")); // false } } |
3. Using List.contains() method
Another option is to convert the array to a list and check if the value exists in the list using the List.contains() method. It returns true if this list contains the specified element; false otherwise. This is a convenient and concise way of solving the problem, but it may have some overhead of creating a new list object. We can also convert the array to a set and use the Set.contains() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Arrays; class Main { public static boolean isPresent(int[] a, int target) { return Arrays.stream(a).boxed().toList().contains(target); } public static<T> boolean isPresent(T[] a, T target) { return Arrays.asList(a).contains(target); } public static void main(String[] args) { System.out.println(isPresent(new int[] { 10, 12, 14, 25, 16 }, 25)); // true System.out.println(isPresent(new String[] { "a", "b", "c" }, "e")); // false } } |
4. Using Apache Commons Lang Library
Another way to determine whether a value is present in an array is to use the Apache Commons Lang library. It provide utility methods for working with arrays, such as checking if an array contains a certain value. For example, we can use the ArrayUtils.contains() method from org.apache.commons.lang3 package. This method returns true if the array contains the specified value. It is overloaded for all primitive types and object arrays. We can use it like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import org.apache.commons.lang3.ArrayUtils; class Main { public static void main(String[] args) { int[] arr = { 10, 12, 14, 25, 16 }; int target = 25; boolean isPresent = ArrayUtils.contains(arr, target); System.out.println(isPresent); // true } } |
5. Using Guava Library
Guava library provides several utility classes pertaining to primitives, like Ints for int, Longs for long, Doubles for double, Floats for float, Booleans for boolean, and so on. Each utility class has contains() method that return true if the array of the corresponding primitive type contains the specified value. We can use it like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import com.google.common.primitives.Ints; class Main { public static void main(String[] args) { int[] arr = { 10, 12, 14, 25, 16 }; int target = 25; boolean isPresent = Ints.contains(arr, target); System.out.println(isPresent); // true } } |
Guava’s Iterables class contains a static utility method indexOf(Iterator, Predicate) that returns the index of the first appearance of the element that satisfies the provided predicate, or -1 if the iterator has no such elements. We can use it to determine if an object array contains a particular object by checking if the returned index is greater or equal to zero.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import com.google.common.collect.Iterators; class Main { public static void main(String[] args) { String[] arr = { "a", "b", "c", "d", "e" }; String target = "d"; boolean isPresent = Iterators.indexOf(Iterators.forArray(arr), target::equals) >= 0; System.out.println(isPresent); // true } } |
6. Using Binary Search
For sorted arrays, we can use binary search algorithm to search a value. The algorithm returns the index of the specified element and a negative value if the element is not present in the array. We can determine whether the array contains an element by simply checking if the computed index is greater or equal to zero. This is a fast and efficient way of approaching this problem, but it requires that the array is sorted in ascending order before searching. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Arrays; class Main { public static void main(String[] args) { int[] sortedArray = { 10, 12, 14, 16, 25 }; int target = 16; boolean isPresent = Arrays.binarySearch(sortedArray, target) >= 0; System.out.println(isPresent); // true } } |
7. Using Linear Search
Finally, we can use a for loop to iterate over the array and compare each element with the value. This is a simple and straightforward approach, but it may be inefficient for large arrays or frequent searches. We can use the == operator for primitive types, or the equals() method for reference types. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Main { public static boolean isPresent(int[] a, int target) { for (int i: a) { if (target == i) { return true; } } return false; } public static<T> boolean isPresent(T[] a, T target) { for (T s: a) { if (target.equals(s)) { return true; } } return false; } public static void main(String[] args) { System.out.println(isPresent(new int[] { 10, 12, 14, 25, 16 }, 25)); // true System.out.println(isPresent(new String[] { "a", "b", "c" }, "e")); // false } } |
That’s all about determining whether a value is present in an array in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)