What’s a Lambda expression in Java?

Tram Ho

Think of a lambda expression as a shortened syntax for the compiler (similar to when we program on IDEs, just typing psvm + Tab will get the function “public static void main (String [] args)”), when The compiler sees the lambda syntax, it expands into two parts: the class definition and the class constructor.
If you think of it as a tool to shorten your code, you’ll love it, to the point where you’ll find ways to utilize it whenever possible.
Let’s take a look at a simple example of a CarMall mall, where there are many different Cars:

In which, CarFilter:

With Car:

If we do the usual way, we will create a class that implements the CarFilter interface:

At that time, the code to print all Honda cars is:

However, if we use a lambda expression, we don’t need to initialize the class implement CarFilter, and the code to print out Honda cars only needs:

This reduces the load of about a dozen lines of code (because there is no need to initialize CarFilterImpl).
But why? How can we code like that and still be understood by the compiler?
In essence, all the information needed to “extend” is already available in the function carMall.showCars (…) . The compiler knows that it needs to pass an object of the class that implements the CarFilter interface into the showCars (CarFilter filter) function , and that this object needs to implement the function: * boolean confirm (Car car) * because it is the only function in the interface. . It also knows that the content in the function will be equivalent to expression: c -> c.getProducer (). Equals (“Honda”) .
From there, the compiler will automatically generate a piece of code like this:

And so the program runs well !! Well, lambda is actually very simple, isn’t it

Share the news now

Source : Viblo