Here's a summary of how to abbreviate lambda expressions. It will be asked in exams such as Java Silver, so I hope it will help the examinees. Finally, I will summarize how to remember.
If you don't understand the lambda expression in the first place, please click here. Understanding Java 8 Lambda Expressions
First, the basic form of the lambda type.
Uninflected word
Predicate<String> javaChecker = (String s) -> { return s.equals("Java"); };
Let's see what can be omitted from here.
First, the argument types are optional.
Predicate<String> javaChecker = (s) -> { return s.equals("Java"); };
However, if there are multiple arguments, it is not possible to omit only one.
//Compile error
BiFunction<Integer, Integer, Integer> adder = (a, Integer b) -> { return a + b; };
The argument () can also be omitted.
Predicate<String> javaChecker = s -> { return s.equals("Java"); };
However, there are two conditions. First, if you specify a type, you cannot omit it.
//Compile error
Predicate<String> javaChecker = String s -> { return s.equals("Java"); };
Second, it cannot be omitted even if there are multiple arguments.
//Compile error
BiFunction<Integer, Integer, Integer> adder = a, b -> { return a + b; };
I think it's good to remember that () is optional only when the argument is one word.
The method {} can also be omitted.
Consumer<String> buyer = goods -> System.out.println(goods + "I bought");
There are also conditions here. First, it cannot be omitted if there are two or more sentences.
//Compile error
Consumer<String> buyer = goods -> String message = "I," + goods;
System.out.println(message + "I bought");
If you write return next, you cannot omit it.
//Compile error
Predicate<String> javaChecker = s -> return s.equals("Java");
However, if you omit return, you can execute it normally.
Predicate<String> javaChecker = s -> s.equals("Java");
Remember that {} can be omitted only when the process is one statement, and if there is a return value, the return can be omitted as a set.
return As mentioned above, return can be omitted, but it cannot be omitted if the method {} is left.
//Compile error
Predicate<String> javaChecker = s ->{ s.equals("Java"); };
Even if you want to omit the return, it will be a set with the omission of {}.
The summary is as follows.
Omitted part | conditions |
---|---|
Argument type | 全Argument typeを省略すること |
Of the argument() | Only for one word |
Of the method{} | Only for one statement If there is a return value, set with omission of return |
return | Of the method{}Omission and set |
Recommended Posts