October 28, 2020

Double Unary Operator Implementation using modern java

DoubleUnaryOperator is a functional interface that lives in java.util.function package.

It has one function applyAsDouble, which takes a double and returns a double.

It is called an UnaryOperator, because it performs it’s action on a single argument.

And, that single argument is of double type that’s why it has Double in it’s name.

We can implement this interface in different ways.

Implementation By a regular class.

private class DBLImple implements DoubleUnaryOperator{
       @Override
   public double applyAsDouble(final double dblValue){
       return dblValue * dblValue;
   }
   }

Implementation By an anonymous class.

final DoubleUnaryOperator dblOp = new DoubleUnaryOperator(){
    @Override
    public double applyAsDouble(final double dblValue){
        return dblValue * dblValue;
    }
};

Implementation 1 –¬† Using Lambda function

final DoubleUnaryOperator dblLambda_1 = (double dblValue) -> { return dblValue * dblValue ; };

Implementation 2 – Using Lambda Function

final DoubleUnaryOperator dblLambda_2 = dblValue -> dblValue * dblValue;

You can watch my youtube video to see me code the implementations.


Full Source Code :-

import java.util.function.DoubleUnaryOperator;

public class DoubleUnaryOperatorImplementation{
    //Implementation by a regular class
    private class DBLImple implements DoubleUnaryOperator{
        @Override
    public double applyAsDouble(final double dblValue){
        return dblValue * dblValue;
    }
    }

    //Anonymous class implementation
    final DoubleUnaryOperator dblOp = new DoubleUnaryOperator(){
        @Override
        public double applyAsDouble(final double dblValue){
            return dblValue * dblValue;
        }
    };

    //Lambda implementation 1
    final DoubleUnaryOperator dblLambda_1 = (double dblValue) -> { return dblValue * dblValue ; };

    //Lambda Implementation 2 
    final DoubleUnaryOperator dblLambda_2 = dblValue -> dblValue * dblValue;

    public static void main(final String... args){
        final DoubleUnaryOperatorImplementation obj = new DoubleUnaryOperatorImplementation();
    final DBLImple dblObj = obj.new DBLImple();
    System.out.println(dblObj.applyAsDouble(12.0));
    System.out.println(obj.dblOp.applyAsDouble(12.0));
    System.out.println(obj.dblLambda_1.applyAsDouble(12.0));
    System.out.println(obj.dblLambda_2.applyAsDouble(12.0));

    }
}