1. Standard Syntax
Consider this example:
String[] arr = {"program", "creek", "is", "a", "java", "site"}; Arrays.sort(arr, (String m, String n) -> Integer.compare(m.length(), n.length())); System.out.println(Arrays.toString(arr)); |
The standard syntax of a lambda expression consists of the following:
- A comma-separated list of formal parameters enclosed in parentheses. In this case, it is
(String m, String n)
- The arrow token
->
- A body, which consists of a single expression or a statement block. In this case, it is one single expression –
Integer.compare(m.length(), n.length())
Output: [a, is, java, site, creek, program]
2. Parameter Type Can be Inferred
If the parameter type of a parameter can be inferred from the context, the type can be omitted.
In the above code, the type of m and n can be inferred to String, so the type can be omitted. This makes the code cleaner and more like a real lambda expression.
String[] arr = { "program", "creek", "is", "a", "java", "site" }; Arrays.sort(arr, (m, n) -> Integer.compare(m.length(), n.length())); System.out.println(Arrays.toString(arr)); |
3. Multiple Lines of Code in Lambda Expression
If the code can not be written in one line, it can be enclosed in {}. The code now should explicitly contain a return statement.
String[] arr = { "program", "creek", "is", "a", "java", "site" }; Arrays.sort(arr, (String m, String n) -> { if (m.length() > n.length()) return -1; else return 0; }); System.out.println(Arrays.toString(arr)); |
Output: [program, creek, java, site, is, a]
4. Single Parameter with Inferred Type
Parenthesis can be omitted for single parameter lambda expression when types can be inferred.
String[] arr = { "program", "creek", "is", "a", "java", "site" }; Stream<String> stream = Stream.of(arr); stream.forEach(x -> System.out.println(x)); |
Output: a is java site creek program
5. Method References
The previous code can also be written as the following by using method references:
Stream<String> stream = Stream.of(arr); stream.forEach(System.out::println); |
6. No Parameter
When no parameter is used for a function, we can also write the lambda expression. For example, it can look like the following:
() -> {for(int i=0; i<10; i++) doSomthing();} |
lambda expression also has certain restrictions in case of exception handling.
Read about it here – http://netjs.blogspot.com/2015/06/lambda-expression-and-exception-handling-java-8.html
Lambda expression may be a whole block of code known as lambda block –
http://netjs.blogspot.in/2015/06/lambda-expression-in-java-8-overview.html