I have a very large list of objects and I want to count number of objects based on one of their attribute. what I have right now is:
long low = myList.stream().filter(p -> p.getRate().equals("Low")).count();
long medium = myList.stream().filter(p -> p.getRate().equals("Medium")).count();
long high = myList.stream().filter(p -> p.getRate().equals("High")).count();
I am not sure how Java 8 handles this but I am worried about performances! Is there anyway so I can count these 3 attributes in one call? in order to improve performance?
Something so that it returns a Map or list of object.
You can group your List
by the rate of each object and count the number of occurences. Assuming your object are of type MyClass
:
Map<String, Long> map = myList.stream().collect(groupingBy(MyClass::getRate, counting()));
This will return a Map
where the key is the rate and the value is the number of elements from the list having that rate. Then, it is simply a matter of getting the "Low"
, "Medium"
and "High"
keys.
groupingBy(classifier, downstream)
is a collector that groups elements according to the given classifier (here, it is MyClass::getRate
) and performs a reduction on the values using the downstream collector (here, it is counting()
).
NB: the following static imports are needed for the code to compile:
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
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