How to pass a Java 8 lambda with a single parameter

你说的曾经没有我的故事 提交于 2021-01-21 10:10:32

问题


I want to simply pass a lambda (chunk of code) and execute it when I need to. How do I implement the method executeLambda(...) in the code below (as well what is the method signature):

public static void main(String[] args)
{
    String value = "Hello World";
    executeLambda(value -> print(value));
}

public static void print(String value)
{
    System.out.println(value);
}

public static void executeLambda(lambda)
{
    someCode();
    lamda.executeLambdaCode();
    someMoreCode();
}

回答1:


Your lambda takes one parameter, but you only pass the lambda to executeLambda, not the value. If you want the lambda to capture the local variable, don't write it taking a parameter, but if you do really want it to take one parameter, you would write it like this:

import java.util.function.Consumer;

public static void main(String[] args) {
    String message = "Hello World";
    executeLambda(message, value -> print(value));
}

public static void executeLambda(String value, Consumer<String> lambda) {
    lambda.accept(value);
}

If you want it to capture the value, then use Runnable, write the lambda as () -> print(value), and call it like runnable.run().




回答2:


public static void main(String[] args)
{
    String value = "Hello World";
    executeLambda(() -> print(value));
}

public static void print(String value)
{
    System.out.println(value);
}

public static void executeLambda(Runnable runnable)
{
    runnable.run();
}



回答3:


By providing a reasonable parameter type. The method taking the lambda does not know about lambdas.

Instead you could pass a Callable object. And then your method has to invoke the call() method on that object! Alternatively, a Runnable or Consumer of String could be used (as a Callable is supposed to return a value - and the method you invoke is void).



来源:https://stackoverflow.com/questions/47482894/how-to-pass-a-java-8-lambda-with-a-single-parameter

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