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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With