Java anyMatch Method: Stream Element Check

In Java, you can use the anyMatch method to check if any element in a Stream satisfies a specified condition.

Here is the usage of the anyMatch method:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

boolean hasEvenNumber = numbers.stream().anyMatch(num -> num % 2 == 0);

if (hasEvenNumber) {
    System.out.println("List contains at least one even number");
} else {
    System.out.println("List does not contain even numbers");
}

In the example above, we created a list of integers called numbers, and then used the stream().anyMatch() method to check if there is any even number in the list. If there is at least one even number in the list, it will output “List contains at least one even number”; otherwise, it will output “List does not contain even numbers”.

bannerAds