Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 ToLongFunction when should I use it?

Tags:

java

java-8

Java 8 now has functional interfaces, such as ToLongFunction which converts its parameter to a long value.

I saw an example as the code below:

ToLongFunction<String> i  = (x)-> Long.parseLong(x);

System.out.println(i.applyAsLong("2"));

The question is: Why should I implement an interface just to convert a variable to a primitive long, where it would be more simple and readable to just call the method Long.parseLong(x)?

like image 425
Gabriel Avatar asked Dec 18 '22 11:12

Gabriel


1 Answers

The short answer is that you wouldn't do that at all, you'd just call Long.parseLong() directly in that case.

The longer answer point is that you rarely explicitly declare explicit variables of the type ToLongFunction as you did with your i above, but rather indirectly use the functional interface as a target when writing a lambda for one of the many functions that take them.

To use an example from the new Stream interface, you may want to take a List<String> input of String objects that have numerical values like: ["123", "456", ...] and parse them all into a list of long.

You can do that with something like:

long[] result = input.stream().mapToLong( x -> Long.parseLong(x) ).toArray(); 

Here you never wrote ToLongFunction directly, but indirectly used it by providing a lambda method to mapToLong(ToLongFunction f), which calls your Long.parseLong(x) method. So the functional interface was the magic that helped make that work.

So you'll make indirect use of this interface all the time with Stream and other lambda related features in Java 8, but you may not use it explicitly very often (unless you are writing classes which want to accept such a function).

like image 105
BeeOnRope Avatar answered Dec 30 '22 16:12

BeeOnRope