Reshma Bidikar

In this blog post, I will be explaining how the Java 8 functional interface DoubleUnaryOperator works. To know more about functional interfaces, you can refer to this blog post.

[table id=24 /]

What is DoubleUnaryOperator

DoubleUnaryOperator is an in-built functional interface in the java.util.Function package. It accepts an argument of double data type, operates on it and produces a result of type double. It is a specialization of the UnaryOperator interface. It has an applyAsDouble method. It applies the logic in this method on the double argument passed in and produces a double result.

DoubleUnaryOperator Code Sample

The following code demonstrates this interface:

DoubleUnaryOperator doubleUnaryOp = num -> Math.sqrt(num);
double input = 9;
double result = doubleUnaryOp.applyAsDouble(input);
System.out.println("result:"+result);

This code prints the following output:

result:3.0

Why DoubleUnaryOperator

The DoubleUnaryOperator interface is a non-generic primitive specialization of the UnaryOperator interface. The other functional interfaces like Supplier, Predicate,Consumer also have primitive specializations like IntSupplier, LongPredicate, IntConsumer, etc. The primitive specializations help to improve performance when the input parameters are of primitive types. For example, in the above example, we can also use a UnaryOperator interface as follows:

UnaryOperator<Double> unaryOp = num -> Math.sqrt(num);
double input = 9;
double result = unaryOp.applyAsDouble(input);
System.out.println("result:"+result);

Conclusion

So in this article, we took a look at the DoubleUnaryOperator interface. This interface is a specialization of the UnaryOperator interface that accepts a double parameter and returns a double result.