简体   繁体   English

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

[英]Java Stream forEach Loop with Multiple Conditions

I have a forEach loop and for performance issues I'm told to use Java stream instead of this.我有一个 forEach 循环,对于性能问题,我被告知使用 Java stream 而不是这个。 I have multiple cases and my code is like below.我有多个案例,我的代码如下所示。 I couldn't found any stream example with multiple cases.我找不到任何具有多个案例的 stream 示例。 Could anyone help me to convert this?谁能帮我转换一下? Thanks a lot in advance.提前非常感谢。

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

For the updated question, Stream API may be used to map the age into Consumer<String> using references to methods methodA, methodB, methodC and then invoke Consumer::accept but this does not seem to be very useful and can be considered just as an exercise:对于更新后的问题,Stream API 可用于 map 使用对方法methodA, methodB, methodC的引用将年龄转换为Consumer<String> ,然后认为它不是很有用,但可以认为是调用此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, 22, 30, 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");
        }
    });

You could just use forEach with your code.您可以将 forEach 与您的代码一起使用。 Not sure if this is what you want or why.不确定这是否是您想要的或为什么。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM