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

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

How can I write an if block using lambda?

问题

  1. String str = "Hello";
  2. String x = "1";
  3. if (Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")
  4. .anyMatch(s -> s.equals(str))) {
  5. if (x != null) {
  6. // do something
  7. } else {
  8. // do something else
  9. }
  10. }
英文:

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

  1. String str = "Hello";
  2. String x = "1";
  3. if(str.equals("Hello") || str.equals("Helloo") ||
  4. str.equals("Hellooo") || str.equals("Hellooo...")) {
  5. if(x != null) {
  6. // do something
  7. } else {
  8. // do something else
  9. }
  10. }

答案1

得分: 4

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

  1. Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")
  2. .filter(str::equals)
  3. .findAny()
  4. .ifPresent(c -> {
  5. if (x != null) {
  6. // 做某事
  7. } else {
  8. // 做其他事情
  9. }
  10. });

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

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

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

英文:

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

  1. Stream.of("Hello", "Helloo", "Hellooo", "Hellooo...")
  2. .filter(str::equals)
  3. .findAny()
  4. .ifPresent(c -> {
  5. if (x != null) {
  6. // do something
  7. } else {
  8. // do something else
  9. }
  10. });

But in your case, I would like to use:

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

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:

确定