JAVA 8 - Lambda Expression
JAVA 8 - Lambda Expression
EXPRESSIONS
pg. 1
Why Java needs Lambda?
One issue with anonymous classes is that if the implementation of your anonymous class is very
simple, such as an interface that contains only one method, then the syntax of anonymous classes
may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an
argument to another method, such as what action should be taken when someone clicks a
button. Lambda expressions enable you to do this, to treat functionality as method argument, or
code as data.
Anonymous Class
Anonymous Class
Syntax
A lambda expression is characterized by the following syntax −
parameter -> expression body
pg. 2
Surface Advantage of Lambdas
• Old
button.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) { doSomethingWith(e);
}
});
• New
button.addActionListener(e -> doSomethingWith(e));
pg. 3
return m athOperation.operation(a, b);
}
}
Scope
Using lambda expression, you can refer to final variable or effectively final variable which is
assigned only once. Lambda expression throws a compilation error, if a variable is assigned a
value the second time.
Scope Example
Java8Tester.java
public class Java8Tester {
final static String salutation = "Hello! ";
public static void m ain(String args[]){
GreetingService greetService1 = m essage ->
System .out.println(salutation + m essage);
greetService1.sayMessage("ABC");
}
interface GreetingService {
void sayMessage(String m essage);
}
}
pg. 4