Lets look at an example of a predicate that filters even numbers then we will use the same predicate to filter odd numbers
While this tutorial maybe basic, until you learn what java 8 methods are available especially when calling the stream filter method, you might want to take the opposite of what predicate is set up for. Instead of rewriting the predicate, you can simply use the
negate property that exist on the
Predicate object. When making this method call, it will return a predicate that represents the logical negation of the predicate. So lets look at an example of a predicate that filters even numbers then we will use the same predicate to filter odd numbers. Also, be sure if your list contains null to remove null values otherwise you could run into a
First lets write a predicate called
isEven that can be passed to
stream.filter and return even numbers.
If a requirement changes that states filter odd numbers, instead of creating a
isOdd predicate we can simply call the
negate() operation on the predicate to get the odd results. We can print stream in java 8 by passing the static println to the foreach.
Just for reference, if you grew up using guava and com.google.common.base.Predicate this example looks slightly different. Instead of calling the
negate method, you will need to call utility method
Predicates.not passing in predicate which will evaluate to true if the given predicate evaluates to false.
Thanks for joining in today's level up, have a great day!