Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform Multiple logics on a stream

Trying out java 8 streams . Is it possible in streams to find the count of elements starting with X , Y , Z from a List which contains a lot of elements.

transactions.stream()
            .filter(e -> startsWith("X"))
            .count();

transactions.stream()
            .filter(e -> startsWith("Y"))
            .count();

transactions.stream()
            .filter(e -> startsWith("Z"))
            .count();

The above code gives the count of elements starting with X,Y,Z in the list but in the above case i'am iterating through the list three times to get the data's. This could be done by iterating the list just once using a simple for loop. Is it possible to do all these conditions in a single stream [iterating just once] instead of using multiple streams ?

Any help is greatly appreciated.

like image 317
Vicky Avatar asked Dec 23 '22 17:12

Vicky


1 Answers

I wouldn't use streams for that. But if you must, have a look at this code:

Map<String, Long> collect = transactions.stream().collect(Collectors.groupingBy(t -> {
    if (t.startsWith("X")) {
        return "X";
    }
    if (t.startsWith("Y")) {
        return "Y";
    }
    if (t.startsWith("Z")) {
        return "Z";
    }
    return "none";
}, Collectors.counting()));

will print something like

{X=1, Y=1, Z=1, none=1}

For the specific case

like image 72
steffen Avatar answered Jan 02 '23 22:01

steffen