Built-in Java 8 predicate that always returns true?

Garret Wilson picture Garret Wilson · Oct 24, 2014 · Viewed 50.2k times · Source

Google Guava has a predicate that always returns true. Does Java 8 have something similar for its Predicate? I know I could use (foo)->{return true;}, but I want something pre-made, analogous to Collections.emptySet().

Answer

Stuart Marks picture Stuart Marks · Oct 24, 2014

There are no built-in always-true and always-false predicates in Java 8. The most concise way to write these is

x -> true

and

x -> false

Compare these to

Predicates.alwaysTrue() // Guava

and finally to an anonymous inner class:

new Predicate<Object>() {
    public boolean test(Object x) {
        return true;
    }
}

Probably the reason that Guava has these built-in predicates is that there is a huge syntactic advantage of a static method call over an anonymous inner class. In Java 8, the lambda syntax is so concise that there is a syntactic disadvantage to writing out a static method call.

That's just a syntactic comparison, though. There is probably a small space advantage if there were a single global always-true predicate, compared to x -> true occurrences spread across multiple classes, each of which would create its own predicate instance. Is this what you're concerned about? The savings didn't seem compelling, which is probably why they weren't added in the first place. But it could be reconsidered for a future release.

UPDATE 2015-04-24

We've considered the addition of a variety of static, named functions such as Predicate.alwaysTrue, Runnable.noop, etc., and we have decided not to add any more in future versions of Java SE.

Certainly there is some value in something that has a name vs. a written-out lambda, but this value is quite small. We expect that people will learn how to read and write x -> true and () -> { } and that their usage will become idiomatic. Even the value of Function.identity() over x -> x is questionable.

There is a tiny performance advantage to reusing an existing function instead of evaluating a written-out lambda, but we expect the usage of these kinds of functions to be so small that such an advantage would be negligible, certainly not worth the API bloat.

Holger also mentioned in comments the possibility of optimizing composed functions such as Predicate.or and such. This was also considered (JDK-8067971) but was deemed somewhat fragile and error-prone, and occurring infrequently enough that it wasn't worth the effort to implement.

See also this Lambda FAQ entry.