How to implement DoubleFunction<R> using lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

The DoubleFunction<R> is a built-in functional interface defined in java.util.function package. This interface accepts one double-valued parameter as input and returns a value of type R. As this is a functional interface, it can be used as an assignment target for a lambda expression or method reference. DoubleFunction<R> interface having only one abstract method, apply().

Syntax

@FunctionalInterface
public interface DoubleFunction<R> {
 R apply(double value);
}

Example

import java.util.function.DoubleFunction;
public class DoubleFunctionTest {
   public static void main(String[] args) {
      DoubleFunction<String> getGrade = marks -> { // lambda expression
         if(marks > 90 && marks <= 100) {
            return "A";
         }
         else if(marks > 70 && marks <= 90) {
            return "B";
         }
         else if(marks > 50 && marks <= 70) {
            return "C";
         }
         else {
            return "D";
         }
      };
      double input = 95;
      System.out.println("Input Marks: " + input);
      String grade = getGrade.apply(input);
      System.out.println("Grade : "+ grade + "\n");
      input = 85;
      System.out.println("Input Marks: " + input);
      System.out.println("Grade : " + getGrade.apply(input) + "\n");
      input = 67;
      System.out.println("Input Marks: " + input);
      System.out.println("Grade : " + getGrade.apply(input) + "\n");
      input = 49;
      System.out.println("Input Marks: " + input);
      System.out.println("Grade : " + getGrade.apply(input));
   }
}

Output

Input Marks: 95.0
Grade : A

Input Marks: 85.0
Grade : B

Input Marks: 67.0
Grade : C

Input Marks: 49.0
Grade : D
raja
Published on 08-Jan-2020 11:29:58
Advertisements