- Introduction to Lambda Expressions
- Lambda Expression Scope
- Method References
- Functional Interfaces
- Default and Static Methods on Interfaces
Java 8 Lambda Expressions: Lambdas, Method References, Static and Default methods on Interfaces.
Introduction to Lambda Expressions
The biggest new feature of Java 8 is language level support for lambda expressions. A lambda expression is like syntactic sugar for an anonymous class with one method whose type is inferred. However, it is not an anonymous class.
Lambda expressions have enormous implications for simplifying development. They make it possible to pass functions as parameters. This is also referred to as "code as data". This simplifies specifying search criteria, callbacks, event handlers, observers and other design patterns.
For example, the following compares creating a simple ActionListener in Java 7 and 8:
// Java 7
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
};
// Java 8
ActionListener al8 = e -> System.out.println(e.getActionCommand());
Lambdas also work nicely with Collections in Java 8. For example, printing out a list of Strings becomes:
// Java 7
for (String s : list) {
System.out.println(s);
}
//Java 8
list.forEach(s -> System.out.println(s));
The main syntax of a lambda expression is "parameters -> body". The compiler can usually use the context of the lambda expression to determine the functional interface (we will explain what "functional interface" means later) being used and the types of the parameters.
There are four important rules to the syntax:
- Declaring the types of the parameters is optional.
- Using parentheses around the parameter is optional if you have only one parameter.
- Using curly brackets
{}is optional (unless you need multiple statements). - The "return" keyword is optional if you have a single expression that returns a value and no curly brackets.
Here are some examples of the syntax:
() -> System.out.println(this)
(String str) -> System.out.println(str)
str -> System.out.println(str)
(String s1, String s2) -> { return s2.length() - s1.length(); }
(s1, s2) -> s2.length() - s1.length()
The last expression could be used to sort a list; for example:
Arrays.sort(strArray,
(String s1, String s2) -> s2.length() - s1.length());
In this case the lambda expression implements the Comparator interface to sort strings by length.
Challenge
Which of the following is not proper syntax?
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Challenge
Use a Lambda expression to print out a list of doubled numbers.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.