[英]How should I define a lambda in my method's arguments?
Ι have the following custom Runnable: Ι 有以下自定义Runnable:
class RandomSum extends Runnable {
public void run() {
float sum - 0;
for(int i = 0; i<1000000;i++){
sum+=Math.random();
}
}
}
And I want to run it like that:我想这样运行它:
RandomSum s =new RandomSum();
s.retrieveCallback((sum)->{
System.out.println(sum);
});
Thread thread = new Thread();
thread.start();
But I do not know how I should define the method retrieveCallback
in RandomSum that accepts a lambda?但我不知道我应该如何在接受 lambda 的 RandomSum 中定义方法retrieveCallback
?
One possible target type of the lambda you've shown is a Consumer
.您展示的 lambda 的一种可能目标类型是Consumer
。 Define a method setCallback
accepting a Consumer<Float>
and store it as an instance variable.定义一个接受Consumer<Float>
的方法setCallback
并将其存储为实例变量。 Then invoke it after the for
loop.然后在for
循环之后调用它。
class RandomSum implements Runnable {
Consumer<Float> callback;
public void setCallback(Consumer<Float> callback) {
this.callback = callback;
}
public void run() {
float sum = 0;
for(int i = 0; i<1000000;i++){
sum += Math.random();
}
callback.accept(sum);
}
}
Caller side主叫方
RandomSum s =new RandomSum();
s.setCallback((sum)->{
System.out.println(sum);
});
Or using method references,或者使用方法引用,
s.setCallback(System.out::println);
Preferably you can pass the callback in the constructor.最好您可以在构造函数中传递回调。
You can define retrieveCallback
within RandomSum
as follows:您可以在RandomSum
中定义retrieveCallback
,如下所示:
public void retrieveCallback(FeedbackHandler feedbackHandler) {
int sum = ...; // Get the value however you like.
feedbackHandler.handleFeedback(sum);
}
And then define this FeedbackHandler
interface as:然后将这个FeedbackHandler
接口定义为:
public interface FeedbackHandler {
void handleFeedback(int sum);
}
Essentially what happens when you pass lambda (sum) -> {...}
to retrieveCallback
is:基本上,当您将 lambda (sum) -> {...}
传递给retrieveCallback
时会发生什么:
retrieveCallback(new FeedbackHandler() {
@Override
public void handleFeedback(int sum) {
...
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.