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

Java 8Object Oriented ProgrammingProgramming

DoubleUnaryOperator is a functional interface defined in java.util.function package. This functional interface expects a parameter of type double as input but produces the output of the same type. DoubleUnaryOperator interface can be used as an assignment target for lambda expression and method reference. This interface contains one abstract method: applyAsDouble(), one static method: identity() and two default methods: andThen() and compose().

Syntax

@FunctionalInterface
public interface DoubleUnaryOperator {
 double applyAsDouble(double operand);
}

Example of Lambda Expression

import java.util.function.DoubleUnaryOperator;
public class DoubleUnaryOperatorTest1 {
   public static void main(String[] args) {
      DoubleUnaryOperator getDoubleValue = doubleValue -> { // lambda expression
         return doubleValue * 2;
      };
      double input = 20.5;
      double result = getDoubleValue.applyAsDouble(input);
      System.out.println("The input value " + input + " X 2 is : " + result);
      input = 77.50;
      System.out.println("The input value " + input+ " X 2 is : " + getDoubleValue.applyAsDouble(input));
      input = 95.65;
      System.out.println("The input value "+ input+ " X 2 is : " + getDoubleValue.applyAsDouble(input));
   }
}

Output

The input value 20.5 X 2 is : 41.0
The input value 77.5 X 2 is : 155.0
The input value 95.65 X 2 is : 191.3


Example of Method Reference

import java.util.function.DoubleUnaryOperator;
public class DoubleUnaryOperatorTest2 {
   public static void main(String[] args) {
      DoubleUnaryOperator d = Math::cos;    // method reference
      System.out.println("The value is: " + d.applyAsDouble(45));

      DoubleUnaryOperator log = Math::log10;    // method reference 
      System.out.println("The value is: " + log.applyAsDouble(100));
   }
}

Output

The value is: 0.5253219888177297
The value is: 2.0
raja
Published on 22-Jan-2020 14:52:00
Advertisements