5 Different Syntax of Lambda Expression

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()));

The standard syntax of a lambda expression consists of the following:

  1. A comma-separated list of formal parameters enclosed in parentheses. In this case, it is (String m, String n)
  2. The arrow token ->
  3. 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())
[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()));

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;
		return 0;
[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));

5. Method References

The previous code can also be written as the following by using method references:

Stream<String> stream = Stream.of(arr);

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();}
Category >> Java 8 >> Lambda Expression  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. infoj on 2015-6-12

    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 –


Leave a comment