Find which element of the stream does not match the given predicate in allmatch

sanchitkum :

I want to find out which element is failing the predicate in case of allmatch.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean isEven = numbers.stream().allMatch(n-> n % 2 == 0);

Here isEven is false, as element 1 fails the predicate.

I can use forEach over the stream to find which element fails like:

numbers.stream().forEach(n -> {
            if (n % 2 != 0)
                System.out.println(n + "is Odd");
        });

Is there a way to figure out which elements fails the predicate in the allmatch when it returns false?

Misha :

Please remember that allMatch is a short-circuiting operation, meaning that the stream API may return false without finding all the elements that fail the test.

So if you want to find all the failing elements, you might have to do more work than a simple allMatch (as shown by other answers). However, if you only care to find one element that fails the test, use findAny as follows:

Optional<Integer> odd = numbers.stream()
    .filter(n -> n % 2 != 0)
    .findAny();

boolean isEven = !odd.isPresent();

odd.ifPresent(x -> System.out.println(x + " is odd"));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=467255&siteId=1