Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java > 8 stream count multiple items at the same time

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.

like image 454
Am1rr3zA Avatar asked Oct 28 '15 19:10

Am1rr3zA


1 Answers

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;
like image 100
Tunaki Avatar answered Nov 15 '22 16:11

Tunaki