In Java 8 different predicate interfaces (ex. DoublePredicate, LongPredicate, IntPredicate, etc.) are provided. Now if you are going to implement the interface and write your own code in it, what is the advantage of having different predicate interfaces ? why not just one predicate interface ?
These different interfaces exist for performance reasons.
Because generics
don't allow primitive types (so far) and they require boxing, the API provides specialisation for primitives so you avoid the cost of boxing and unboxing.
The point of these specialized predicate interfaces is to avoid unnecessary auto-(un)boxing when you are working with primitives.
For example, if you need to use a Predicate
that works on int
values you can use IntPredicate
with which you can pass an int
directly to the test(...)
method, instead of a Predicate<Integer>
which requires boxing to an Integer
object.
Note that in Java, it is not possible to use primitive types as type arguments (so, Predicate<int>
is not allowed).
There are not just Predicates
but also other functional interfaces with type-specific variants. The reason is, the support primitive types.
While the general version could be used with object types (including Double
, Long
, etc), there is no way for using primitives with generics. I.e.
Predicate<int> p; //does not compile
For example, the IntStream
operates on int
and not on Integer
, but you can't use Object-typed Functional Interfaces on int
values, so you need int-specific variants of the functional interfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With