Java program to check if an array contains a given value
Here's a Java program to check if an array contains a given value:
import java.util.Arrays; public class ArrayContainsValue { public static void main(String[] args) { int[] numbers = { 1, 2, 3, 4, 5 }; int value = 3; if (containsValue(numbers, value)) { System.out.println("The array contains the value " + value); } else { System.out.println("The array does not contain the value " + value); } } public static boolean containsValue(int[] array, int value) { return Arrays.stream(array).anyMatch(x -> x == value); } }Source:www.theitroad.com
In this program, we first define an array of integers called numbers
and the value we want to search for, called value
. We then call a function called containsValue
to check if the array contains the value we're looking for. If the function returns true
, we print a message indicating that the array contains the value, and if the function returns false
, we print a message indicating that the array does not contain the value.
The containsValue
function takes an integer array and an integer value as input and returns a boolean indicating whether the value is present in the array or not. The function uses the Arrays.stream
method to convert the array to a stream of integers, and then uses the anyMatch
method to check if any of the elements in the stream are equal to the given value. If any element in the array is equal to the given value, the function returns true
, otherwise it returns false
.
You can modify the values of numbers
and value
to search for different values in different arrays.