Engineering Full Stack Apps with Java and JavaScript
Lambda expressions implement an interface with only one single abstract methodl. Such interfaces are called as functional interfaces. Since the interface has only one single method (function), passing across that interface implementation gives the impression of passing across that function. Already existing interfaces in Java such as Runnable, Comparator, ActionListener are already functional interfaces, as they have only one abstract method. We will see how we can use lambda expressions with those existing interfaces.
Basic syntax of lambda expression is:
(input arguments) -> body.
The body may return anything in accordance to the return type of the functional interface. In case, if the body contains more than one statements, those statements can be put within curly braces.
Before
<NEED-TO-ADD>
With Lambda expression
new Thread( () -> System.out.println("Hello from run.")).start();
Before
Collections.sort(stringList, new Comparator<String> ()){
@Override
public int compare(String s1,String s2){
return s1.compareToIgnoreCase(s2);
}
});
With Lambda expression:
Comparator <String> c = (s1,s2) -> return s1.compareToIgnoreCase(s2);
Collections.sort(stringList,c);
Before:
button.addActionListener (new ActionListener() ){
public void actionPerformed( ActionEvent event){
System.out.println(“button clicked”);
}
});
With Lambda expression:
button.addActionListener ( event -> System.out.println(“button clicked”);
Note that event is the name of the parameter which can be used within code and its type is inferred from context automatically by Java.
Give exampe for Callable (Single line and multi-line)