英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论