In Java, what is the purpose of special interfaces like IntFunction, LongFunction?

Similarly, we have different interfaces for Int* , Double* , Long* , corresponding Function , Supplier , Predicate .

It seems to me that the only advantage of using these special interfaces is to make the code more readable and make its clients use only this particular type for input.

But also, did I miss some other use cases?

+5
source share
2 answers

The purpose of these interfaces is to allow working with primitive types directly. This saves automatic boxing and automatic unpacking, which makes these interfaces (and the related IntStream , LongStream and DoubleStream that depend on them) more efficient.

For example, instead of using Function<Integer,R> , which has a method that accepts Integer and creates a result of type R , you use IntFunction<R> , which has a method that accepts int and produces a result of type R If you pass an int this function, you will avoid the box that would happen if you pass the same int method to the Function<Integer,R> method.

+6
source

IntPredicate accepts int as input, not Predicate<Integer> , which accepts Integer , so basically there is no boxing / unboxing.

It also introduces additional methods for primitives, for example, for example, IntStream#sum .

+4
source

Source: https://habr.com/ru/post/1275214/


All Articles