Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what purpose do special interfaces like IntFunction, LongFunction serve? [duplicate]

Tags:

java

java-8

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

It seems to me that the only benefit of using these special interfaces is to have code that is more readable and enforces its clients to use only that specific type as input.

But apart from, am I missing some other use cases?

like image 255
Saket Mehta Avatar asked Feb 07 '18 13:02

Saket Mehta


People also ask

What is IntFunction?

Interface IntFunction<R> Represents a function that accepts an int-valued argument and produces a result. This is the int -consuming primitive specialization for Function . This is a functional interface whose functional method is apply(int) . Since: 1.8 See Also: Function.

Which functional interface does Java provide to serve as data types for lambda expressions?

function Description. Functional interfaces provide target types for lambda expressions and method references.

What is function interface in Java?

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods.


1 Answers

The goal of these interfaces is to allow working with primitive types directly. This saves auto-boxing and auto-unboxing, and therefore makes these interfaces (and the related IntStream,LongStream and DoubleStream that depend on them) more efficient.

For example, instead of using a Function<Integer,R> that has a method that accepts an Integer and produces a result of type R, you use an IntFunction<R> that has a method that takes an int and produces a result of type R. If you pass an int to that function, you avoid the boxing that would take place if you passed the same int to the Function<Integer,R>'s method.

like image 117
Eran Avatar answered Oct 03 '22 02:10

Eran