How can I write with Java 8 with closures support a method that take as argument a function and return function as value?
In Java Lambda API the main class is java.util.function.Function.
You can use a reference to this interface in the same way as you would do with all other references: create that as variable, return it as a result of computation and so on.
Here is quite simple example which 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 then 1 parameter, please take a look into compose
method, but its usage is quite tricky.
In general from my opinion closures and lambdas in Java is basically syntax-sugar, and they seem to not have all capabilities of functional programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With