Thursday, August 16, 2018

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 do the conversion, return double value of the integer. It can be used in lambda expression as well as method references.

 Syntax

public IntToDoubleFunction{
double applyAsDouble(int a)
}
applyAsDouble method applies to given integer argument and returns the result of the method.

Lambda IntToDoubleFunction usage example

 The below code explains about 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 is
8.0
3.5

Method reference IntToDoubleFunction usage 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 is
2.5
5.0

Related article


EmoticonEmoticon