- Programming paradigm
- Not the same as procedural programming
- Allows you to pass anonymous functions as parameters
- Implemented in Java 8 through lambda expressions
- Used to simplify code
(parameters) -> { function body }
Using Lambda Expressions as Functional Interfaces
You can use lambda expressions to replace interface implementations that have only a single method.
Here's a typical way to create a thread using a Runnable object.
Thread thread = new Thread( new Runnable() {
public void run() {
System.out.println("Hello");
}
});
thread.start();
You can use a lambda expression to replace an interface with a single method:
Thread thread = new Thread(
() -> {
System.out.println("Hello");
}
);
thread.start();
Adding Parameters
Here's a typical way to create an ActionListener. The ActionListener interface only has a single method called actionPerformed(ActionEvent e).
JTextField textField = new JTextField();
JLabel label = new JLabel();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
label.setText(event.getActionCommand());
}
});
You can add parameters to lambda expressions as well. Here's the equivalent code using lambda expressions.
JTextField textField = new JTextField();
JLabel label = new JLabel();
textField.addActionListener((ActionEvent event) -> {
label.setText(event.getActionCommand());
});
The above code can even be simplified further by eliminating the type of the parameter.
JTextField textField = new JTextField();
JLabel label = new JLabel();
textField.addActionListener(event -> {
label.setText(event.getActionCommand());
});
Hope this simple tutorial helped you get started with Lambda expressions!
Gavin Lim is the lead Java instructor of ActiveLearning, Inc. http://www.activelearning.ph
No comments:
Post a Comment