11

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.

3
  • 1
    How would you do it with a for loop? Why wouldn't you do the same with a stream? Before optimizing, have you measured and proven a performance problem? Commented Oct 28, 2015 at 19:16
  • with loop I just iterate over all items and check the value of getRate() and update the value of map with specific key, and no I didn't measure the performance. Commented Oct 28, 2015 at 19:20
  • 1
    Why use a Map when you could use an object with three fields? Start by measuring. Commented Oct 28, 2015 at 19:21

1 Answer 1

22

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;
Sign up to request clarification or add additional context in comments.

1 Comment

This solution will only return count for a particular key only when this key is present in the initial list i.e. with the list consisting of only High and Low values this solution will not return 0 for Medium key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.