Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why different predicate interfaces n JAVA 8?

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 ?

like image 968
Milind Vinkar Avatar asked Jun 14 '16 13:06

Milind Vinkar


3 Answers

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.

like image 128
Sleiman Jneidi Avatar answered Oct 08 '22 06:10

Sleiman Jneidi


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).

like image 36
Jesper Avatar answered Oct 08 '22 06:10

Jesper


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.

like image 4
Gerald Mücke Avatar answered Oct 08 '22 06:10

Gerald Mücke