What is a lambda expression and where does it apply?
Answer 1, authority 100%
Lambda Expressions are a new feature in Java 8 (like method references ), which allows you to implement partial functional sugar, so to speak. In other words, lambdas allow you to break a little from the standard paradigm in Java – OOP, and add a little functionality to the language, make it more flexible.
Actually, lambda expressions are created in the first place to make it easier to write code. By themselves, they are very similar to anonymous classes.
I think it will be easier to understand by example. Let’s say you want to create and start a new thread. You can do this in several ways:
- Create a class that implements the functional Runnable interface and add an instance of it to the Thread parameters
- Create anonymous class directly inside Thread constructor parameters
- Use this very know-how and write everything through lambdas
First:
class RunnableImpl implements Runnable {
@Override
public void run () {
System.out.println ("Hello world from new thread");
}
}
...
...
Thread thread = new Thread (new RunnableImpl ()); // Normal use of a class object
Second:
Thread thread = new Thread (new Runnable () {
@Override
public void run () {
// Anonymous class simplifies code and adds functionality
System.out.println ("Hello world from new thread");
}
});
Third:
Thread thread = new Thread (() - & gt; System.out.println ("Hello world from new thread via lambda ")); // As you can see, everything is very simple here
Then, for each of these examples, call thread.start ();
and enjoy the result.
As you can see from the 3rd example, lambdas are based on a special syntax (this is not clear () - & gt;
). In order to understand this, you first need to generally understand in what cases lambdas are used, or rather, where it is permissible by the syntax of the language. I emphasized one important word – functional interface , and this is what lambdas work with. A functional interface is an interface that has only one method (like Runnable has only one run method).
You can write your own functional interface. Here:
interface CalculateEngine {
double add (double a, double b);
}
And then, use lambdas
CalculateEngine calculateEngine = ((a, b) - & gt; a + b);
System.out.println (calculateEngine.add (4.5, 3.2)); // 7.7
Similarly, you can do this through anonymous classes (to better understand what and how)
CalculateEngine calculateEngine = new CalculateEngine () {
@Override
public double add (double a, double b) {
return a + b;
}
};
System.out.println (calculateEngine.add (4.5, 3.2)); // 7.7
It can be inferred that lambda expressions are used wherever convenient. Creating streams, working with collections. Wherever functional interfaces are taken as a basis.
p.s: more, I would like to tell you that such things are better reading in different books / articles and etc. So-like, similar questions already set . It is very important to be able to google .