Lambda expressions and higher-order functions

穿精又带淫゛_ 提交于 2019-12-19 17:37:15

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/15198979/lambda-expressions-and-higher-order-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!