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

Java 8Object Oriented ProgrammingProgramming

LongToDoubleFunction is a built-in functional interface and part of java.util.function package. This functional interface accepts a long-valued parameter as input and produces a double-valued result. LongToDoubleFunction can be used as an assignment target for a lambda expression or method reference. It contains only one abstract method: applyAsDouble().

Syntax

@FunctionalInterface
interface LongToDoubleFunction {
 double applyAsDouble(long value);
}

Example of Lambda Example

import java.util.function.LongToDoubleFunction;
public class LongToDoubleLambdaTest {
   public static void main(String args[]) {
      LongToDoubleFunction getDouble = longVal -> { // lambda expression
         double doubleVal = longVal;
         return doubleVal;
      };
      long input = 565758L;
      System.out.println("The input is: " + input);
      double result = getDouble.applyAsDouble(input);
      System.out.println("The result is: " + result);
   }
}

Output

The input is: 565758
The result is: 565758.0


Example of Method Reference

import java.util.function.LongToDoubleFunction;

public class LongToDoubleMethodRefTest {
   public static void main(String args[]) {
      LongToDoubleFunction result = LongToDoubleMethodRefTest::convertLongToDouble;   // method reference
      System.out.println(result.applyAsDouble(75));
      System.out.println(result.applyAsDouble(60));
   }
   static Double convertLongToDouble(long value) {
      return (double)value / 5;
   }
}

Output

15.0
12.0
raja
Published on 27-Jan-2020 18:08:26
Advertisements