Lambda Expressions
Learn about lambda expressions and their syntax.
Introduction
The biggest new feature of Java 8 is the language level support for lambda expressions (Project Lambda). A lambda expression is like syntactic sugar for an anonymous class with one method whose type is inferred. However, it will have huge implications for simplifying development.
Syntax
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 being used and the type of the parameters. There are four important rules to the syntax:
- Declaring the type of the parameters is optional.
- Using parentheses around the parameter is optional if we have only one parameter.
- Using curly braces is optional (unless we need multiple statements).
- The
return
keyword is optional if we have a single expression that returns a value.
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 ...
Access this course and 1400+ top-rated courses and projects.