Java API 8 API

This question is related to displaying and grouping elements using java 8 assemblers. I have a list of patients. Each patient has a list of departments he visited. Let's say I want to calculate for each department how many times it has been visited using the new collector APIs in java 8, how would I group by the list of departments?

Thanks!

NOTE: I know that I can put a counter in each of the departments, this question is intended solely for exploring the new functions of java 8.

the code:

public class Patient { private String id; private List<Department> history; /* some more getters/setters come here */ } 

In my main method, I have a list of patients. I want to know for each department how many times it has been visited, without editing the Department class (or expanding or decorating it).

I think I need to take a stream of patients and display them on a dept-> account card (how many times each patient has visited this department). Having a stream of these cards - I have no idea what to do to group these cards and count them.

+7
java mapping java-8 collectors
source share
1 answer

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); 
+11
source share

All Articles