First, I assume that if a Patient has visited the Department more than once, that Department will appear in the patient history list more than once.
If so, then we can simply take our patient stream and flatMap it into the department stream, where the appearance of the department indicates one visit to the patient.
Then we can pass this to the groupingBy collector. We want to classify by the department itself, so the classifier function is an identification function.
For the value, we want to put the value 1 in the value if the record for the Department is not already specified, but we want to add 1 to the existing value if the record is present. There, the collector is called counting() , which does this for us already, so we just pass it as a downstream collector to groupingBy() .
The resulting code is as follows:
import static java.util.stream.Collectors.*; List<Patient> patients = ... ; Map<Department, Long> frequency = patients.stream() .flatMap(p -> p.getHistory().stream()) .collect(groupingBy(d -> d, counting()));
Please note that if the department has not been visited, it will simply not be on the map. If you have a list of departments, you can fill in the null values ββas follows:
departments.forEach(d -> frequency.putIfAbsent(d, 0L));
or if you want to fill in the zero on the get side,
long numVisits = frequency.getOrDefault(dept, 0L);
Stuart marks
source share