Lambda expressions and higher order functions

How can I write with Java 8 with closure, supporting a method that takes a function as an argument and a return function as a value?

+7
source share
1 answer

In the Java Lambda API, the main class is java.util.function.Function .

You can use the link to this interface in the same way as with all other links: create it as a variable, return it as a result of calculations, etc.

Here is a pretty simple example that might help you:

public class HigherOrder { public static void main(String[] args) { Function<Integer, Long> addOne = add(1L); System.out.println(addOne.apply(1)); //prints 2 Arrays.asList("test", "new") .parallelStream() // suggestion for execution strategy .map(camelize) // call for static reference .forEach(System.out::println); } private static Function<Integer, Long> add(long l) { return (Integer i) -> l + i; } private static Function<String, String> camelize = (str) -> str.substring(0, 1).toUpperCase() + str.substring(1); } 

If you need to pass more than 1 parameter, check out the compose method, but using it is quite difficult.

In general, in my opinion, closure and lambda in Java are basically sugar syntax, and they don't seem to have all the features of functional programming.

+11
source

All Articles