简体   繁体   中英

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. I have multiple cases and my code is like below. I couldn't found any stream example with multiple cases. 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:

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. 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);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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