What is Lamdba Expression
Lambda Expressions are at the heart of Java SE 8. A “Lambda Expression” is a block of code that you can pass around so it can be executed later, once or multiple times.
Lambda
Expressions are Closures or anonymous methods that provide developers
with a simple and compact means for representing behavior as data.
- The use or lambda expression improves readability, performance and reusability
- The use of lambda expressions is all about abstracting complexity away into libraries
- The use of lambda expressions improves developer productivity
For example: If
one wants to model a workflow such as ` do A before you start, do B for
each file in the file group, do C upon error and do D after you
finish`, than one needs to break the phases of the workflow & the
client code has to be directly involved in each phase.
=> Java (before java8) lacks in tools which can express the behavior from A to D. It also affects the APIs design.
Things to Remember in Lambda Expressions :
- A lambda expression is a block of code with parameters.
BinaryOperator add = (long x, long y) -> {
x+y
}
- Use a lambda expression whenever you want a block of code executed at a later point in time.
Runnable myRunnable = () -> {
System.out.Println("Executing the Run method inside the Runnable!!!");
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println("Running at a deferred time > "+df.format(date));
}
- Lambda expressions can be converted to functional interfaces.
- Lambda expressions can access effectively final or final variables from the enclosing scope.
public void enclosingMethod() {
final String IamFinalVariable = "This is an immutable final variable";
Button button = new Button("click me");
button.addActionListener( event -> System.out.println(IamFinalVariable);
String IamEffectivelyFinalVariable = "This is effectively final variable. Its value should not change in this scope.";
IamEffectivelyFinalVariable = "Do not try to change me. Otherwise compiler will error out";
JRadioButton finalRadioButton = new JRadioButton("Final Var Selected");
finalRadioButton.setActionCommand(IamFinalVariable);
JRadioButton effectiveFinalRadioButton = new JRadioButton("Effective Final Var Selected");
effectiveFinalRadioButton.setActionCommand(IamEffectivelyFinalVariable);
ButtonGroup group = new ButtonGroup();
group.add(finalRadioButton);
group.add(effectiveFinalRadioButton);
ActionListener selectOrDeselect = event -> {
System.out.println("You are talking to >"+ event.getActionCommand( ));
}
}
- Method and constructor references refer to methods or constructors without invoking them.
- You can now add default and static methods to interfaces that provide concrete implementations.
- You must resolve any conflicts between default methods from multiple interfaces
No comments:
Post a Comment