java.util.function.DoubleToLongFunction is a primitive specialization of Other Functional Interfaces. What it means is , we can get the same functionality using other functional interfaces, but they are going to be slow.

Because of boxing and unboxing. If you are dealing with Double and Long wrapper objects then use other functional interface.

So, this functional interface is not very heavy. It has only one abstract method, that takes a double and returns a long.

I really don’t know of the cases, where I will use it. Still, I have two examples, which shows the way to provide an implementation. I really have hard time figuring out examples. As, I am trying to be as original as possible, I don’t copy and paste from other sites.

Ok,

We will see two implementations here.

  1. Cast a double to long value
  2. math.round a double to long value

Cast a double to long

DoubleToLongFunction castToLong = (dblValue) -> (long) dblValue;

Round a double value to nearest long value.

DoubleToLongFunction roundToLong = Math::round;

Here is the code, which uses above implementations to provide meaningful output.

import java.util.function.DoubleToLongFunction;
import static java.lang.System.out;

public class DoubleToLongFunctionTest {
    public static void main(String ... commandLineArguments){
        double dbl = 12.1212;
        //Cast to Long                                                                                                                                                                                             
        DoubleToLongFunction castToLong = (dblValue) -> (long) dblValue;
        out.printf("Casting :: Double :- %f Long :-%d \n" , dbl, castToLong.applyAsLong(dbl));

        //Another thing that we can do it here is                                                                                                                                                                  
        // use math library to round a double number to long                                                                                                                                                       
        dbl = 12.9212;
        DoubleToLongFunction roundToLong = Math::round;
        out.printf("Rounding :: Double :- %f Long :- %d \n", dbl, roundToLong.applyAsLong(dbl));
    }
}

And here is the output that comes through above code.

Casting :: Double :- 12.121200 Long :-12 
Rounding :: Double :- 12.921200 Long :- 13

In the first case i.e of casting, we see that the decimal part is truncated.

In the second case, we see that the double value is permoted to next greater whole number.

I don’t know how useful these examples are, but it is good enough to provide a meaningful implementation for this interface.

Bye Bye Bye…