Java element displays multiple elements at the same time

I have a very large list of objects, and I want to calculate the number of objects based on one of their attributes. what i have right now:

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'm not sure how Java 8 handles this, but I'm worried about the performances! Anyway, can I take these 3 attributes in one call? in order to increase productivity?

Something to return a map or list of objects.

+4
source share
1 answer

You can group Listby the speed of each object and count the number of occurrences. Assuming your object is of type MyClass:

Map<String, Long> map = myList.stream().collect(groupingBy(MyClass::getRate, counting()));

Map, - , - , . "Low", "Medium" "High".

groupingBy(classifier, downstream) , ( MyClass::getRate) ( counting()).

NB: :

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
+9

Source: https://habr.com/ru/post/1613545/


All Articles