One of the big highlights of Java 8 is the introduction of lambda expressions, which are more concise with the code they are designed for. When a developer writes a lambda expression, it is also compiled into a functional interface. The following example uses lambda syntax instead of an anonymous inner class, and the code is not only concise, but also readable. There is no old way to use lambda:
12345 |
button.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.out.println( "Actiondetected" ); } }); |
Using lambda:
123 |
button.addActionListener(()->{ System.out.println( "Actiondetected" ); }); |
Let's look at a more obvious example. Old ways to not use lambda:
123456 |
Runnable runnable1= new Runnable(){ @Override public void run(){ System.out.println( "RunningwithoutLambda" ); } }; |
Using lambda:
123 |
Runnable runnable2=()->{ System.out.println( "RunningfromLambda" ); }; |
As you can see, the use of lambda expressions not only makes the code simple, but also readable, and most importantly, the amount of code that is reduced a lot. However, in some ways, these functions are already widely used in these JVM languages such as Scala.
Java lambda expression