![]() |
VOOZH | about |
Given an array of integers and a key element, the task is to check whether the key is present in the array. If the key exists, return true; otherwise, return false.
Example:
Input: arr[] = [3, 5, 7, 2, 6, 10], key = 7
Output: Is 7 present in the array: true
Input: arr[] = [-1, 1, 5, 8], key = -2
Output: Is -2 present in the array: false
In the Linear Search method, each element of the array is sequentially compared with the key until a match is found or the end of the array is reached.
Example:
Is 7 present in the array: true
Explanation:
Binary Search efficiently finds an element in a sorted array by repeatedly dividing the search interval in half.
The built-in Arrays.binarySearch() method performs this operation in logarithmic time.
Syntax:
public static int binarySearch(data_type[] arr, data_type key)
Return Value: Returns the index of the key if found; otherwise, a negative value.
Parameters:
Example:
Is 17 present in the array: false
The contains() method of the List interface checks if a specific element exists in a list. We can convert an array to a list using Arrays.asList().
Syntax:
public boolean contains(Object element)
Parameter: It takes a single parameter Object which to be searched in the given list.
Return Type: It return a boolean value, if the element is present in the list return true, otherwise return false.
Example:
Is 7 present in the array: true
The anyMatch() method checks whether any element in a stream matches the provided predicate. It short-circuits as soon as a match is found.
Syntax:
boolean anyMatch(Predicate<T> predicate)
Parameter: This method takes a single parameter predicate of type T which is a generic.
Return Types: This method return a boolean value, True if the element is present otherwise return false.
Example 1: Using IntStream.of()
Is 7 present in the array: true
Example 2: Using Arrays.stream() method to create Stream
Is 7 present in the array: true