Meaning of lambda () -> { } in Java

风格不统一 提交于 2019-12-22 01:13:23

问题


I am looking at the following Stack Overflow answer: How to change Spring's @Scheduled fixedDelay at runtime

And in the code there is the following line:

schedulerFuture = taskScheduler.schedule(() -> { }, this);

I would like to know what the lambda () -> {} means in that code. I need to write it without using lambdas.


回答1:


Its a Runnable with an empty run definition. The anonymous class representation of this would be:

new Runnable() {
     @Override public void run() {
          // could have done something here
     }
}



回答2:


Lamda expression is an anonymous function that allows you to pass methods as arguments or simply, a mechanism that helps you remove a lot of boilerplate code. They have no access modifier(private, public or protected), no return type declaration and no name.

Lets take a look at this example.

(int a, int b) -> {return a > b}

In your case, you can do something like below:

schedulerFuture = taskScheduler.schedule(new Runnable() {
     @Override 
     public void run() {
        // task details
     }
}, this);



回答3:


For lambdas:

Left side is arguments, what you take. Enclosed in () are all the arguments this function takes

-> indicates that it's a function that takes what's on the left and passes it on to the right for processing

Right side is the body - what the lambda does. Enclosed in {} is everything this function does

After you figure that out you only need to know that that construction passes an instance of matching class (look at what's the expected argument type in the schedule() call) with it's only method doing exactly the same as the lambda expression we've just analyzed.




回答4:


Lambda expressions basically express instances of functional interfaces. In a way Lambda expression will be: (lambda operator params) -> {body}

() -> System.out.println("This means Lambda expression is not taking any parameters");

(p) -> System.out.println("Lambda expression with one parameter: " + p);



来源:https://stackoverflow.com/questions/52292953/meaning-of-lambda-in-java

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