Delayed execution using lambda programming

The main reason for using lambda expressions is to delay the execution of the code to an appropriate point in time.

All lambda expressions are deferred. After all, if you want to execute a piece of code immediately, you don't have to use lambda expressions. There are many reasons for delaying code execution, such as:

Run code in another thread run code multiple times run code at the correct point in time for an algorithm (for example, compare operations in sorting) run code when something happens (button click, data arrival, etc.) when you use lambda for programming, you should consider what effect you want to achieve. For example, suppose you need to log an event:

logger. info(“x:”+x+”,y:”+y);

If the log level is set to ignore info messages, the string will be calculated and passed to the info method, and then determine whether to execute it. Why can't you combine strings when you're sure you need to print?

Run the code only when you need it again, which is a case of using lambda expressions. The usual method wraps this code into a parameterless lambda expression: () - > "X:" + X + ", Y:" + y.

Encapsulated into a method to perform delayed logging, which is as follows.

Supplier < string > as a parameter, you can pass a lambda expression.

Of course, you can also write logger directly info(()->”x:”+x+”,y:”+y); It works like this.

Original text from: https://www.fastmeteor.com/2017/12/20/ Delayed execution using lambda programming

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>