How to implement IntToDoubleFunction using lambda and method reference in Java?


IntToDoubleFunction is a functional interface from java.util.function package. This functional interface accepts an int-valued argument and produces a double-valued result. IntToDoubleFunction can be used as an assignment target for a lambda expression or method reference. It contains only one abstract method: applyAsDouble().

Syntax

@FunctionalInterface
interface IntToDoubleFunction {
   double applyAsDouble(int value);
}

Example of Lambda Expression

import java.util.function.IntToDoubleFunction;;

public class IntToDoubleLambdaTest {
   public static void main(String[] args) {
      IntToDoubleFunction getDouble = intVal -> {      // lambda expression
         double doubleVal = intVal;
         return doubleVal;
      };

      int input = 25;
      double result = getDouble.applyAsDouble(input);
      System.out.println("The double value is: " + result);

      input = 50;
      System.out.println("The double value is: " + getDouble.applyAsDouble(input));

      input = 75;
      System.out.println("The double value is: " + getDouble.applyAsDouble(input));
   }
}

Output

The double value is: 25.0
The double value is: 50.0
The double value is: 75.0


Example of Method Reference

import java.util.function.IntToDoubleFunction;

public class IntToDoubleMethodRefTest {
   public static void main(String[] args) {
      IntToDoubleFunction result = IntToDoubleMethodRefTest::convertIntToDouble; // method reference
      System.out.println(result.applyAsDouble(50));
      System.out.println(result.applyAsDouble(100));
   }
   static Double convertIntToDouble(int value) {
      return value / 10d;
   }
}

Output

5.0
10.0

raja
raja

e

Updated on: 14-Jul-2020

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements