Built-in Java 8 predicate that always returns true?
Let us aim for easiness with this simple TODO-like lambda!
This lambda expression symbolizes a predicate that always evaluates to true
, no matter the object that it is called with.
Diving into the subject of predicates
Lambda, our simple but powerful tool
In Java 8, there's no specific always-true or always-false predicate function in the standard library, but the functionality can be smoothly handled by lambda expressions. Compared to anonymous inner classes, lambdas are compact and add essential brevity.
Reusing is the new recycling
Remember the predicate represented by x -> true
? It's simple, but even this can be inlined by the JVM at runtime, saving unnecessary overhead. Plus, using it globally reduces code duplication and the risk of errors.
Options from our Code-neighborhood
Even though standard Java doesn't offer dedicated always-true/false predicates, third-party libraries such as Guava and Spring come to the rescue. For example, Spring's data-util library has Predicates.isTrue()
and Predicates.isFalse()
for similar functionality:
And the SE proposal myth goes bust...
A common myth in the developer community is that Java SE rejected a proposal to add static, named functions for always-true predicates. But guess what? No such proposal was ever formally submitted.
Let's dive deeper into lambda expressions
Easy reading and writing
The lambda s -> true
seems simple, but it dramatically boosts code readability and maintainability compared to the old way of anonymous classes.
Predicates: The multi-talented performers
Predicates can be chained or composed using .and()
and .or()
. But be careful, a chaining frenzy could leave you with a slow and fragile concoction.
Become a lambda master
For more enlightenment, do check out Angelika Langer's Lambda FAQ. It's a one-stop shop for all things lambda in Java.
Was this article helpful?