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

Java 8Object Oriented ProgrammingProgramming

DoubleBinaryOperator is a functional interface defined in java.util.function package. It accepts two parameters of type double as input and produces another double value as a result. DoubleBinaryOperator interface can be used as an assignment target for a lambda expression or method reference and has only one abstract method applyAsDouble().

Syntax

@FunctionalInterface
public interface DoubleBinaryOperator {
 double applyAsDouble(double left, double right);
}

Example-1

import java.util.function.DoubleBinaryOperator;

public class DoubleBinaryOperatorTest {
   public static void main(String args[]) {
      // using lambda expression
      DoubleBinaryOperator sum = (d1, d2) -> d1 + d2;
      DoubleBinaryOperator mul = (d1, d2) -> d1 * d2;
      DoubleBinaryOperator div = (d1, d2) -> d1 / d2;
      DoubleBinaryOperator sub = (d1, d2) -> d1 - d2;

      System.out.println("Sum = " + operate(sum, 15, 10));
      System.out.println("Multiplication = " + operate(mul, 15, 10));
      System.out.println("Division = " + operate(div, 15, 10));
      System.out.println("Subtraction = " + operate(sub, 15, 10));
   }
   private static double operate(DoubleBinaryOperator operator, double d1, double d2) {
      return operator.applyAsDouble(d1, d2);
   }
}

Output

Sum = 25.0
Multiplication = 150.0
Division = 1.5
Subtraction = 5.0


Example-2

import java.util.function.DoubleBinaryOperator;

public class DoubleBinaryOperatorTest1 {
   public static void main(String[] args) {
       // Using Lambda Expression
      DoubleBinaryOperator lamdaTest = (d1, d2) -> DoubleBinaryOperatorTest1.mutiply(d1, d2);
      System.out.println(lamdaTest.applyAsDouble(7, 5));
      // Using Method reference
      DoubleBinaryOperator methodRefTest = DoubleBinaryOperatorTest1::mutiply;
      System.out.println(methodRefTest.applyAsDouble(10, 5));
   }
   public static double mutiply(double d1, double d2) {
      return d1 * d2;
   }
}

Output

35.0
50.0
raja
Published on 10-Jan-2020 11:00:32
Advertisements