微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有多个条件的 Java Stream forEach 循环

如何解决具有多个条件的 Java Stream forEach 循环

我有一个 forEach 循环,对于性能问题,我被告知使用 Java 流而不是这个。我有多个案例,我的代码如下。我找不到任何包含多个案例的流示例。有人可以帮我转换这个吗?非常感谢。

name = "Serena";
for(Integer age : ages){
   if(age>10 && age<20)
        methodA(name);
   else if(age>20 && age<30)
        methodB(name);
   else
        methodC(name);

解决方法

对于更新的问题,Stream API 可用于使用对方法 Consumer<String> 的引用将年龄映射到 methodA,methodB,methodC,然后调用 Consumer::accept 但这似乎不是很有用并且可以视为练习:

public static void main(String .... args) {
    List<Integer> ages = Arrays.asList(1,10,15,20,22,30,33);

    ages.stream()
        .map(MyClass::byAge)
        .forEach(action -> action.accept("Serena"));
}

// mapper to specific method
static Consumer<String> byAge(int age) {
    return 10 < age && age < 20
            ? MyClass::methodA
            : 20 < age && age < 30
            ? MyClass::methodB
            : MyClass::methodC;
}

// consumer methods
public static void methodA(String name) {
    System.out.println("A: " + name);
}

public static void methodB(String name) {
    System.out.println("B: " + name);
}

public static void methodC(String name) {
    System.out.println("C: " + name);
}
,
List<Integer> ints = Arrays.asList(11,40);

ints.forEach(i -> {
        if (i> 10 && i < 20) {
            System.out.println("Value between 10 & 20");
        } else if(i >= 20 && i < 30) {
            System.out.println("Value between 20 & 30");
        } else if(i>=30 && i <40) {
            System.out.println("Value between 30 & 40");
        }
    });
,

您可以将 forEach 与您的代码一起使用。不确定这是您想要的还是为什么。

ages.forEach(age -> {
    if(age > 10 && age < 20) {
        methodA(age);
    }
    else if(age > 20 && age < 30) {
        methodB(age);
    }
    else {
        methodC(age);
    }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。