Search code examples
javainterfacepredicatefunctional-interface

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 ?


Solution

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