5

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 ?

Milind Vinkar
  • 159
  • 1
  • 9
  • 1
    A more interesting question would by by do some primitive types and not others. ;) – Peter Lawrey Jun 14 '16 at 13:28
  • 1
    @PeterLawrey actually it is why not BooleanStream,CharStream .... ? Brian said some where that it would increase the footprint of the JDK for APIs that a rarely use. – Sleiman Jneidi Jun 14 '16 at 13:32
  • @SleimanJneidi while it is probably the reason, I don't image that compressed class files which are never used increase the footprint that much. – Peter Lawrey Jun 14 '16 at 13:35

4 Answers4

10

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.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
9

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

Jesper
  • 202,709
  • 46
  • 318
  • 350
4

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.

Gerald Mücke
  • 10,724
  • 2
  • 50
  • 67
0

These specialized predicate interfaces are provided to support primitive data type like int or float without autoboxing. Without them we have to convert our int data to Integer Object to use in Predicate interface.

http://codedestine.com/java-8-predicate-interface/

lalitbhagtani
  • 459
  • 5
  • 6
  • **Just a small correction:** there are no specialized functional interfaces for the `float` data type. IMHO, wrappers for `int`, `long` and `double` are available, but that's it. – Priidu Neemre Feb 15 '19 at 13:54