convert for each to stream with if else

Viewed 92

i have a code scenario where i'm converting a for each to stream , but I'm not sure if this is the correct approach i follow

This is the for each loop:

List<ClassA> list=getList(); //Contains object of type ClassA
int a=0; int b=0; int c=0;
for(ClassA a: list) {
    String response=checkRespone(a.getId());
    if(reponse.equals("x"))  ++a;
    else if(reponse.equals("y")) ++b;
    else ++c;
}

To convert it into stream i wrote this. IS there a better way to write this ?

AtomicInteger a = new AtomicInteger(0);
AtomicInteger b = new AtomicInteger(0);
AtomicInteger c = new AtomicInteger(0);

list.stream().forEach(ClassA->{if(checkRespone(a.getId()).equals("x")) {a.set(a.get()+1);} else if (checkRespone(a.getId()).equals("y")) {
    b.set(b.get()+1);
} else {
    c.set(c.get()+1);
}});
1 Answers

If you really want to perform this functionally, you can try out grouping collectors. You can further avoid iterating the values to find their sum if you tend to use the size of the initial list to find the remaining count for variable c.

Map<String, Long> countingResponse = list.stream()
        .map(clz -> checkRespone(clz.getId()))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int a = countingResponse.getOrDefault("x", 0L).intValue();
int b = countingResponse.getOrDefault("y", 0L).intValue();
int c = list.size() - (a + b);
Related