![]() |
VOOZH | about |
In Java, to check if a specified element is present in an array, we have to iterate through the array and compare each element with the target value. This can be done using loops, utility functions, or Java 8 Streams.
Example: The simplest way to check if an element is present in an array is by using a for loop.
3 is present in the array.
This method encapsulates the logic of checking element presence in an array, making the code reusable and cleaner. The utility function takes an array and the target element as inputs and returns a boolean result.
25 is not present in the array.
Arrays.asList() for Non-Primitive ArraysFor non-primitive arrays (like String or Integer), we can use the Arrays.asList() method to convert the array into a list and then check for the presence of the element using contains().
"Charlie" is present in the array.
Explanation: The Arrays.asList(names) converts the array to a List and the contains(target) checks if the List contains the specified element.
The Streams API in Java 8 provides a concise way to check if an element exists in the array.
4 is present in the array.
Explanation: The IntStream.of(numbers)converts the array into a stream of integers and the anyMatch(num -> num == target) returns true, if any element matches the condition.