Java 8 - IntToDoubleFunction functional interface example

IntToDoubleFunction is a functional interface in java.util.function package.

It is introduced in java8. It has one abstract method -applyAsDouble takes an int as input and does the conversion, returning the double value of the integer. It is used in lambda expression as well as method references.

Here is an IntToDoubleFunction Syntax

public IntToDoubleFunction{
        double applyAsDouble(int a)
}

applyAsDouble method applies to given integer argument and returns the result of the method.

IntToDoubleFunction Lambda expression example

The below code explains the usage of applyAsDouble() using lambda expression with an example.

import java.util.function.IntToDoubleFunction;
public class intToDoubleLambdaDemo {
    public static void main(String[] args) {
        IntToDoubleFunction function = (number) -> (number / 10d);
        System.out.println(function.applyAsDouble(80));
        System.out.println(function.applyAsDouble(35));
    }
}

Output:

8.0
3.5

IntToDoubleFunction Method reference example

The below shows how to use method reference with IntToDoubleFunction method applyAsDouble with an example.

import java.util.function.IntToDoubleFunction;

public class intToDoubleMethodRefDemo {

    static Double convertIntToDouble(int value) {
        return value / 10d;
    }
    public static void main(String[] args) {
        IntToDoubleFunction IntToDoubleFunction = intToDoubleMethodRefDemo::convertIntToDouble;
        System.out.println(IntToDoubleFunction.applyAsDouble(25));
        System.out.println(IntToDoubleFunction.applyAsDouble(50));
    }
}

Output:

2.5
5.0

Conclusion

In this tutorial, Learn IntToDoubleFunction class using lambda expression and method reference example with applyAsDouble method.