Why does Java have Predicate<T> when Function<T,Boolean> seems to do the same job, and what does each cost or offer?
answer
- primitive or reference result
- what a null result does
- what Stream.filter declares
- combinators live on only one
- Boolean.valueOf's shared constants
basics
~10 sPredicate<T> is the boolean-returning function shape: test returns primitive boolean, so it cannot yield null, and it adds and, or and negate. APIs like Stream.filter declare Predicate. Function<T,Boolean> suits generic APIs wanting a Function.
solid answer
~50 s`Predicate<T>` is the shape `java.util.function` defines for `T` to `boolean`, with `boolean test(T)`; the package has no `ToBooleanFunction`, and `Predicate` fills that slot. It offers three things over `Function<T,Boolean>`: a primitive result that cannot be `null`, the combinators `and`, `or` and `negate` plus static `not` and `isEqual`, and being what `Stream.filter`, `Collection.removeIf` and `Optional.filter` declare. `Function<T,Boolean>` returns a reference, so a caller using it as a condition casts and unboxes, and a `null` result throws `NullPointerException` at the unboxing. javac boxes a result through `Boolean.valueOf`, which returns `Boolean.TRUE` or `Boolean.FALSE`, so compiled code allocates nothing per call, and null safety and API fit matter more than speed. The two types are unrelated: passing a `Function<T,Boolean>` variable to `filter` does not compile, though `f::apply` adapts it. Use `Function<T,Boolean>` only where a generic API wants `Function<T,R>`, such as `Collectors.groupingBy`.
code
java · 30 linesimport java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
class PredicateVsFunction {
public static void main(String[] args) {
Predicate<String> blank = String::isBlank;
Function<String, Boolean> blankFn = String::isBlank;
List<String> words = List.of("a", " ", "b");
System.out.println(words.stream().filter(blank.negate()).toList()); // [a, b]
// words.stream().filter(blankFn); // does not compile: not a Predicate
System.out.println(words.stream().filter(blankFn::apply).count()); // 1
Map<Boolean, List<String>> grouped = words.stream().collect(Collectors.groupingBy(blankFn));
System.out.println(grouped.keySet()); // [false, true]
Function<String, Boolean> unknown = s -> null;
try {
if (unknown.apply("a")) {
System.out.println("not reached");
}
} catch (NullPointerException e) {
System.out.println("unboxing null threw NullPointerException");
}
}
}go deeper
Recall that Predicate has test returning a primitive boolean, and that Stream.filter and removeIf declare it. Function<T,Boolean> looks similar but is a different type that returns a Boolean object.
Explain the mechanics: R erases to Object, so a condition needs a cast and an unboxing, Boolean.valueOf reuses two constants, and a null result throws at the unboxing. Name the adapters f::apply and p::test.
Show the production judgment: a nullable Boolean in a filtering path is a late NullPointerException waiting for a rare input. Type such parameters as Predicate, and adapt only at the boundary with a generic API.
Set the team default: Predicate for yes-or-no parameters, and an enum where a third answer is real. Treat Function<T,Boolean> in a public signature as a review question, since it invites a null and blocks the combinators.
## What each interface declares `java.util.function` is the JDK's package of general-purpose **functional interfaces**: interfaces with one abstract method, which a lambda or method reference can implement. Its package documentation lists `Predicate` as a basic shape in its own right, a "unary function from T to boolean", beside `Function`, a "unary function from T to R". The `Predicate` Javadoc calls it a "boolean-valued function". | | `Predicate<T>` | `Function<T,Boolean>` | |---|---|---| | Abstract method | `boolean test(T t)` | `R apply(T t)`, with `R` as `Boolean` | | Possible results | `true` or `false` | `true`, `false` or `null` | | Default methods | `and`, `or`, `negate` | `compose`, `andThen` | | Static methods | `isEqual`, `not` (Java 11) | `identity` | | Declared by, for example | `Stream.filter`, `Collection.removeIf`, `Optional.filter`, `Collectors.partitioningBy` | `Stream.map`, `Collectors.groupingBy`, each generic over the result | ## Why the library has both - **A primitive result needs its own interface.** A type argument cannot be primitive, so `Function<T,boolean>` does not exist. The package's `ToIntFunction` naming would suggest a `ToBooleanFunction`, and there is none: `Predicate` fills that slot. - **The combinators belong to the boolean case.** `and`, `or` and `negate` only make sense for yes-or-no results, so they live on `Predicate`. On a `Function<T,Boolean>`, `f.negate()` fails with `cannot find symbol`, and the nearest equivalent is `f.andThen(b -> !b)`. - **The name states the intent.** `test` reads as a yes-or-no check at the call site, and a parameter typed `Predicate<Order>` tells the reader that no third answer is possible. ## What `Function<T,Boolean>` costs The compiled code shows the difference. Calling a `Predicate` is `invokeinterface java/util/function/Predicate.test:(Ljava/lang/Object;)Z`, which returns a primitive directly. Using a `Function<String,Boolean>` as a condition takes three instructions, because `R` erases to `Object`: ```text invokeinterface java/util/function/Function.apply:(Ljava/lang/Object;)Ljava/lang/Object; checkcast java/lang/Boolean invokevirtual java/lang/Boolean.booleanValue:()Z ``` That leads to three separate points: - **No allocation from javac's boxing.** javac compiles a lambda returning `s.isEmpty()` to a call of `Boolean.valueOf`, through its internal `Lower.boxPrimitive`, and that method returns the existing `Boolean.TRUE` or `Boolean.FALSE`. So the claim that each call allocates a `Boolean` is wrong for javac-compiled code. This is javac's output, not a language rule: JLS 5.1.7 promises shared objects only for constant expressions, and `s.isEmpty()` is not one. - **A small per-call overhead.** The callee's `Boolean.valueOf`, the cast and the unboxing are extra work on every non-null result, though that is rarely what decides the choice. - **A third state.** A `Boolean` reference can be `null`. `if (f.apply(x))` with a `null` result throws `NullPointerException` at the unboxing (JLS 5.1.8), often far from the code that produced the `null`. A `Predicate` lambda returning `null` does not compile: `<null> cannot be converted to boolean`. ## They do not convert to each other The same lambda text fits either type, because a lambda takes its type from its target and a `boolean` result is boxed when the target wants a reference (JLS 15.27.3). Once in a variable, the two are unrelated, since neither interface extends the other: - `Predicate<String> p = f;` fails: `Function<String,Boolean> cannot be converted to Predicate<String>`. - `stream.filter(f)` fails the same way, because `Stream.filter` declares `Predicate<? super T>`. - `stream.map(p)` fails in the other direction, because `Stream.map` declares `Function`; `stream.map(p::test)` gives a `Stream<Boolean>`. - `(Predicate<String>) f` compiles, then throws `ClassCastException` at run time for an `f` made from a lambda, whose class does not implement `Predicate`. - `f::apply` and `p::test` adapt in each direction. The adapter keeps the hazard: a `null` from `f` becomes a `NullPointerException` inside `test`. Overloads depend on the lambda's style. With `m(Predicate<String>)` and `m(Function<String,Boolean>)`, the call `m(s -> s.isEmpty())` is ambiguous, while `m((String s) -> s.isEmpty())` picks the `Predicate` overload, because JLS 15.12.2.5 prefers the primitive return for an explicitly typed lambda whose results are standalone primitive expressions. ## Choosing between them - Use `Predicate<T>` for any yes-or-no test, and as the parameter type when you design an API that takes one. - Use `Function<T,Boolean>` only where a generic API wants `Function<T,R>` and `Boolean` is merely its result type. `Collectors.groupingBy` is the usual case, and its map holds only the keys that occurred. For a yes-or-no split, `Collectors.partitioningBy` takes a `Predicate` and returns both keys, with an empty list for a side with no elements. - Do not use a `null` `Boolean` to mean "unknown". An enum with a named third case tells the reader what the three answers are, and it cannot throw at an unboxing. How `and`, `or` and `negate` compose, and what they return, is a topic of its own. The reason to prefer `Predicate` here is simpler: it is the type the JDK's filtering APIs declare, and its result cannot be `null`.
- Does a Java Function<T,Boolean> allocate a new Boolean object on every call?Not in javac-compiled code. javac boxes through `Boolean.valueOf`, which returns the existing `Boolean.TRUE` or `Boolean.FALSE`. The per-call cost is a `checkcast` and a `booleanValue()` at the call site. An allocation would need an explicit `new Boolean(...)`, a constructor deprecated since Java 9 whose Javadoc calls it rarely appropriate.
- How do Collectors.partitioningBy with a Predicate and Collectors.groupingBy with a Function<T,Boolean> differ in the map they return?`partitioningBy` returns both keys: a side with no elements maps to an empty list. `groupingBy` holds only keys that occurred, so `get(true)` can return `null`. A `null` from its classifier throws `NullPointerException` with `element cannot be mapped to a null key`. For a yes-or-no split, `partitioningBy` fits better.
- If a Java method is overloaded on Predicate<String> and Function<String,Boolean>, what happens when you pass it a lambda?An implicitly typed lambda, `s -> s.isEmpty()`, gives `reference to m is ambiguous`. An explicitly typed one, `(String s) -> s.isEmpty()`, picks the `Predicate` overload, because JLS 15.12.2.5 prefers the primitive return when each result expression is a standalone primitive expression.
- Function<T,Boolean> allocates a new Boolean on every call, which is why Predicate exists.
- Predicate extends Function<T,Boolean>, so a Predicate can be passed wherever that Function is expected.
- Stream.filter accepts a Function<T,Boolean> variable because both produce a yes-or-no result.
- Predicate.test can return null to signal that the answer is unknown.
- Function<T,Boolean> has negate and and, because every functional interface gets the combinators.
- java.util.function.Predicate
- Java 1.8
- java.util.function.Function
- Java 1.8
- java.util.stream.Stream, including filter
- Java 1.8
- Boolean.valueOf(boolean)
- Java 1.4
Assumes Java 27; Predicate and Function date from Java 8 and Predicate.not from Java 11, and the behaviour shown is the same at Java 25.
context
- Predicate (Java SE 27 & JDK 27)docs.oracle.com
- Chapter 5. Conversions and Contextsdocs.oracle.com
- Lower.java at jdk-27-gagithub.com