如何通过单个参数传递Java 8 lambda [英] How to pass a Java 8 lambda with a single parameter
问题描述
我只想传递一个lambda(代码块)并在需要时执行它.如何在下面的代码中实现方法executeLambda(...)
(以及什么是方法签名):
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();
}
推荐答案
您的lambda带有一个参数,但是您只能将lambda传递给executeLambda
,而不是值.如果您想让lambda捕获局部变量,请不要将其写为带参数,但是如果您确实希望它使用一个参数,则可以这样写:
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);
}
如果希望它捕获value
,请使用Runnable
,将lambda写为() -> print(value)
,然后像runnable.run()
那样调用它.
If you want it to capture the value
, then use Runnable
, write the lambda as () -> print(value)
, and call it like runnable.run()
.
这篇关于如何通过单个参数传递Java 8 lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!