Learn how to check if a value is present in an array in Java 8 using Arrays.stream() and anyMatch() with a simple example and output.
Code Explanation (Step-by-Step) :
- Create an integer array with multiple values.
- Create a variable value to store the number that needs to be searched.
- Use Arrays.stream(arr) to convert the array into an IntStream .
- Use anyMatch(a -> a == value) to check whether the given value exists in the array.
- Store the result in the boolean variable check.
- Print the boolean result.
- If the value is present, the output will be true; otherwise, it will be false.
import java.util.Arrays;
public class CheckValueStatus {
public static void main(String[] args) {
int arr[] = {2, 4, 6, 8, 9};
int value = 6;
boolean check = Arrays.stream(arr)
.anyMatch(a -> a == value);
System.out.println("This " + value + " is present in the array: " + check);
}
}
Output :
This 6 is present in the array: true
Check If a Value Is Present in an String Array in Java 8
import java.util.Arrays;
public class CheckStringValue {
public static void main(String[] args) {
String[] names = {"Amit", "Rahul", "Santosh", "Vijay"};
String value = "Santosh";
boolean result = Arrays.asList(names).contains(value);
System.out.println("Is " + value + " present in the array? " + result);
}
}
Output :
Is Santosh present in the array? true
Here are some Java 8 related programs that will help you understand concepts better :
FAQ
What does anyMatch() do in Java 8?
The anyMatch() method checks whether at least one element in the stream matches the given condition. It returns true if a match is found; otherwise, it returns false.
Is anyMatch() a terminal operation?
Yes, anyMatch() is a terminal operation in the Java Stream API. Once it is executed, the stream processing is completed.
Which package is required to use anyMatch() in Java 8?
We need to import the java.util.Arrays package when using Arrays.stream().
Can I use anyMatch() with String arrays?
Yes, you can use anyMatch() with String arrays.below are the program.
String[] names = {"John", "David", "Mike"};
boolean present = Arrays.stream(names)
.anyMatch(name -> name.equals("David"));
System.out.println(present);