Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expressions and higher-order functions

How can I write with Java 8 with closures support a method that take as argument a function and return function as value?

like image 213
xdevel2000 Avatar asked Mar 04 '13 10:03

xdevel2000


1 Answers

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.

like image 136
n1ckolas Avatar answered Oct 22 '22 14:10

n1ckolas