[英]Lambda expression if-else statement
Hello I Just started learning Lambda expressions, how do I write this with Lambda expressions? 您好,我刚刚开始学习Lambda表达式,如何用Lambda表达式编写?
public static void greaterThanFive(String str){
if(str.length() > 5){
System.out.println("String length is larger than 5 ");
}else{
System.err.println("String length less than 5");
}
if it was just an, if statement I could just do this: 如果只是一个if语句,我可以这样做:
Predicate<String> greaterThanFive = (s)-> s.length() > 5;
But I can't really figure out when it's an if-else statement. 但是我真的不知道什么时候是if-else语句。
Comparator<String> c = (String first, String second) -> {
if (first.length() < second.length()) return -1;
else if (first.length() > second.length()) return 1;
else return 0;
};
I believe this answers your question. 我相信这可以回答您的问题。 For more info, read Java8 for really impatient. 有关更多信息,请阅读Java8以防万一。 Its a really good book. 这是一本非常好的书。
Using blocks, you can create lambda expressions that have multiple statements or big statements (like an if-else). 使用块,您可以创建具有多个语句或大型语句(如if-else)的lambda表达式。 Example: 例:
new Thread( () -> { // Btw, you can use java.lang.Runnable with a lambda
System.out.println("A wild NEW THREAD appeared!"); // :)
try {
Thread.sleep(5000);
} catch (InterruptedException e) {}
System.out.println("Enemy NEW THREAD ran away!");
});
This means all you have to do is to enclose that if-else in the block of a lambda: 这意味着您要做的就是将if-else括在lambda块中:
Consumer<String> greaterThanFive = (s) -> {
// ...
};
Note that there's a semicolon after the block. 请注意,该块后面有一个分号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.