Learn to create a Predicate with the negating effect that will match all the elements not matching the original predicate. The negated predicate acts as a pass function and selects all the elements from the stream that were filtered out by the original predicate.
1. Predicate negate() Method
The Predicate.negate()
method returns the logical negation of an existing predicate.
Predicate<Integer> isEven = i -> i % 2 == 0;
Predicate<Integer> isOdd = isEven.negate();
Use these predicates as follows with the Stream filter() method.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Predicate<Integer> isEven = i -> i % 2 == 0;
Predicate<Integer> isOdd = Predicate.not( isEven );
List<Integer> evenNumbers = list.stream()
.filter(isEven)
.collect(Collectors.toList());
List<Integer> oddNumbers = list.stream()
.filter(isOdd)
.collect(Collectors.toList());
2. Predicate not() Method – Java 11
In Java 11, Predicate
class has a new method not()
. It returns a Predicate that is the negation of the supplied predicate.
Internally, this is accomplished by returning the result of the calling predicate.negate()
.
Predicate<Integer> isEven = i -> i % 2 == 0;
Predicate<Integer> isOdd = Predicate.not( isEven );
Drop me your questions related to Java stream predicate negate examples.
Happy Learning !!