button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

System.out.println("button clicked");

}

});

Unnecessary piece of code: Does not that seem unnecessary piece of code (boilerplate) when there is just the need of only printing the statement “button clicked”?

Does not that seem unnecessary piece of code (boilerplate) when there is just the need of only printing the statement “button clicked”? Why Create Object when all that is needed is to manifest a behavior?: Does not that look like a limitation posed by Java to create an object in order to manifest the behavior of printing “button clicked”?

The above can be avoided by use of what is termed as Lambda Expressions. Lambda expression can be used to easily associate behavior of printing “button clicked” without having need of boilerplate code in following manner:

ActionListener actionListener = event -> {

System.out.println( “button clicked” )

};

button.addActionListener( actionListener );

Note that boilerplate code is no more needed. The code also becomes easy to read and understand. The above code represents that the fact that one argument “event” is passed to the code inside the braces.

Lambda Expression with No Arguments

This is used to implement Runnable interface which has got just one method such as run() that takes no argument and return void type.

Runnable runnable = () -> System.out.println(“Hello World”);

OR,

Runnable runnable = () -> {

System.out.print(“Hello”);

System.out.println(” World”);

};



Lambda Expression with Multiple Arguments

Below represents examples when there are multiple arguments for methods and which need to be represented as Lambda expression:

BinaryOperator<Long> add = (x, y) -> x + y;

BinaryOperator<Long> addExplicit = (Long x, Long y) -> x + y;

Above represents Lambda expression assigned to “add” variable which is equivalent to method with two argument x, and y and statement that adds up x and y. Note that “add” variable does not store the value of addition of x and y. However, it represents the code that adds up the variable.