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()));
System.out.println(Arrays.toString(arr));

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

1 thought on “5 Different Syntax of Lambda Expression”

Leave a Comment