Explain Codes LogoExplain Codes Logo

Built-in Java 8 predicate that always returns true?

java
lambda-expressions
predicate-functions
java-8-features
Alex KataevbyAlex Kataev·Jan 30, 2025
TLDR

Let us aim for easiness with this simple TODO-like lambda!

Predicate<Object> alwaysTrue = x -> true;

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.

// No-need-to-ask Predicate - always grants permission! Predicate<Object> myConstantCompanion = x -> true;

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.

// Go Green, Reuse when possible Predicate<Object> ecoFriendlyPredicate = myConstantCompanion;

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:

// When in Spring, do as the Springers do import org.springframework.data.util.Predicates; Predicate<Object> alwaysTrue = Predicates.isTrue(); Predicate<Object> alwaysFalse = Predicates.isFalse();

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.

// "s -> true" is the predicate equivalent of an all-you-can-eat buffet. Predicate<Object> allYouCanEat = s -> true;

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.

// Predicates combined - like Butter, they're smooth, but just don't overload! Predicate<Object> overloadExample = allYouCanEat.and(allYouCanEat).or(allYouCanEat);

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.