Four Ways to Negate a Predicate in the Steam API's Filter Method
In Java there are various ways to negate a predicate in the Stream API's filter method. In this post I present four approaches.
Join the DZone community and get the full member experience.Join For Free
There are various ways to negate the predicate passed to the filter method of the Stream API. In this blog post, I present four ways to code this negation.
1. Use the Negate Method of the Predicate API
The first approach is to take advantage of the Predicate API's negate() method. This is perhaps how you might have thought about doing it first off and would look something like the following:
but here are some alternative approaches.
2. Write a Predicate Utility Method
You can simplify this approach by writing a utility method that is capable of performing the negation.
Which results in much neater code.
The utility method can of course be reused throughout the application.
3. Use an Identity Function to Convert the Method Reference to a Predicate
With this approach you use a utility method to convert a method reference to a predicate.
although the code is not as neat.
References: Heinz’s Lambda Reduction Principle
4. Use the Not (!) Operator
Finally you can use the familiar,
The code is much simpler and immediately familiar.
It is argued that method references are often harder to read and are trickier when refactoring than simple lambdas and that mixing lambdas and method references in a
Stream chain is confusing to the reader.
When you use a method reference and want the IDE to create the method, IntelliJ creates this as a static method with the object as the first argument. Using the
not operator avoids this.
Published at DZone with permission of Alex Theedom, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.