如何使用 lambda 表达式编写 if 代码块?

huangapple go评论63阅读模式
英文:

How can I write an if block using lambda?

问题

String str = "Hello";
String x = "1";

if (Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")
        .anyMatch(s -> s.equals(str))) {
    if (x != null) {
        // do something
    } else {
        // do something else
    }
}
英文:

Could you please tell me how can I write this expression using lambda/ Java 8 ?

String str = "Hello";
String x = "1"; 

if(str.equals("Hello") || str.equals("Helloo") || 
         str.equals("Hellooo") || str.equals("Hellooo...")) {
   if(x != null) {
       // do something
   } else {
       // do something else 
   }
}

答案1

得分: 4

你可以使用一个Set来存储所有的问候语,然后使用filter和ifPresent来制定条件:

Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")
        .filter(str::equals)
        .findAny()
        .ifPresent(c -> {
            if (x != null) {
                // 做某事
            } else {
                // 做其他事情
            }
        });

但在你的情况下,我建议使用以下方式:

if (str.matches("Hell[o]{1,4}(\\.{4})?")) {
    if (x != null) {
        // 做某事
    } else {
        // 做其他事情
    }
}

关于正则表达式,你可以根据你的输入进行改进,我只是快速制作了一个示例来展示另一种解决方案。

英文:

You can use a Set to store all your salutations, and then use filter and ifPresent to make your condition:

Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")
        .filter(str::equals)
        .findAny()
        .ifPresent(c -> {
            if (x != null) {
                // do something
            } else {
                // do something else
            }
        });

But in your case, I would like to use:

if (str.matches("Hell[o]{1,4}(\\.{4})?")) {
    if (x != null) {
        // do something
    } else {
        // do something else
    }
}

About the regex, you can improve it based on your inputs, I made a quick one to show you the other solution.

huangapple
  • 本文由 发表于 2020年4月9日 20:11:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/61120869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定