13. Lambda Expression
A lambda expression is an “anonymous
function”
a method without a declaration (access
modifier, return value declaration, and name)
Syntax: (argument) -> (body)
(int a, int b) -> { return a + b; }
() -> System.out.println("Hello World");
(String s) -> { System.out.println(s); }
() -> 42
() -> { return 3.1415 };
14. Lambda Example 1
//Old way:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello from thread");
}
}).start();
//New way:
new Thread(
() -> System.out.println("Hello from thread")
).start();
15. Lambda Example 2
//Old way:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("The button was clicked using old fashion code!");
}
});
//New way:
button.addActionListener( (e) -> {
System.out.println("The button was clicked. From lambda expressions !");
});
16. Lambda Example 3
public static void main(String[] args) {
int number = 5;
ObjectCallback callback = () -> {
return (number = number + 1);
};
Object result = callback.Callback();
System.out.println(result);
}
number should be effectively final
17. Conclusion
A closure is any function which closes over
the environment in which it was defined.
A lambda is just an "anonymous function" - a
function defined with no name.
Lambda in Java 8 is NOT closure!