The DoubleFunction<T>
is a Functional Interface. A functional interface has only one abstract method. And it is annotated by @FunctionalInterface
annotation. While it is not mandatory to do that, it is recommended to do that, because compiler will catch the error, if you try to keep more that one abstract method in it.
As the name suggest, the DoubleFunction takes one parameter of double value. And returns a value of type T, here T can be any type.
For example, we can use it to implement different interfaces that are provided by java as specialized cases.
The interface DoublePredicate
can be defined as DoubleFunction<Boolean>
, where we take a double-type as input and return a boolean.
The interface DoubleUnaryOperator
can be defined as DoubleFunction<Double>
, where input and output parameters are double.
Coming back to DoubleFunction, it has only one method, and it is an abstract method.
- R apply(double value) :- It has one parameter of type double and returns a result of type R.
In this tutorial, we will look at two examples, first where we convert a double into a String, and in second we will create an object of Engine Class.
The Engine class has a constructor which has one parameter of type double.
static class Engine { private double horsePower; protected Engine(final double horsePower) { this.horsePower = horsePower; } @Override public String toString() { return "Engine Horse Power is " + horsePower; } }
So, we should begin with the coding part now. 🙂
Convert a double to string :- Here R is replaced with String.
DoubleFunction<String> convertDoubleToString = (dblValue) -> dblValue + " is part of string now ... hahaha :-)";
Create an object using Method Reference :- Here R is replaced with Engine class.
DoubleFunction<Engine> createNewEngineOfGivenHorsePower = Engine::new;
We can print these lambdas to see their string format.
System.out.println(convertDoubleToString.apply(12.0)); System.out.println(createNewEngineOfGivenHorsePower.apply(1223.5) + " hp" );
Output :-
12.0 is part of string now ... hahaha :-) Engine Horse Power is 1223.5 hp
Complete Code :-
import java.util.function.DoubleFunction; public class DoubleFunctionTest { static class Engine { private double horsePower; protected Engine(final double horsePower) { this.horsePower = horsePower; } @Override public String toString() { return "Engine Horse Power is " + horsePower; } } public static void main(String ... args) { //Concatenate with string to make it a string DoubleFunction<String> convertDoubleToString = (dblValue) -> dblValue + " is part of string now ... hahaha :-)"; System.out.println(convertDoubleToString.apply(12.0)); //Using method reference to create an object DoubleFunction<Engine> createNewEngineOfGivenHorsePower = Engine::new; System.out.println(createNewEngineOfGivenHorsePower.apply(1223.5) + " hp" ); } }