I investigated the variation of writing style for lambda expressions introduced in Java8. I will cover it in a tabular format so that you can easily refer to it when you get lost.
No. | Notation | Description |
---|---|---|
1 | () -> System.out.println("foo") | No arguments |
2 | (n) -> System.out.println(n) | With arguments(Enclose in parentheses) |
3 | (int n) -> System.out.println(n) | With arguments(Enclose in parentheses + type specification) |
4 | n -> System.out.println(n) | With arguments(Do not enclose in parentheses) * Parentheses can be omitted only when there is one argument |
5 | (m, n) -> m+n | With arguments(Multiple) |
6 | (int m, int n) -> m+n | With arguments(Multiple + type specified) |
7 | (n) -> { return n * 2;} | Statement type lambda expression |
The above sample code.
// No.1 No arguments
Runnable lambda1 = () -> System.out.println("foo");
// No.2 with arguments(Enclose in parentheses)
IntConsumer lambda2 = (n) -> System.out.println(n);
// No.With 3 arguments(Enclose in parentheses + type specification)
IntConsumer lambda3 = (int n) -> System.out.println(n);
// No.4 with arguments(Do not enclose in parentheses)* Parentheses can be omitted only when there is one argument
IntConsumer lambda4 = n -> System.out.println(n);
// No.5 with arguments(Multiple)
IntBinaryOperator lambda5 = (m, n) -> m+n;
// No.6 with arguments(Multiple + type specified)
IntBinaryOperator lambda6 = (int m, int n) -> m+n;
// No.7 Statement type lambda expression
IntUnaryOperator lambda7 = (n) -> { return n * 2;};
-[C #] Lambda style writing variation -[Java] Super introduction to Java 8 lambda (writing style, functional interface, original definition, lambda receiving process) -Standard functional interface -Basics of using Java8 lambda expressions -Java8 Lambda Summary
Recommended Posts