I have a collection (as hashmap) of Doctors, into a generic Hospital class.
Map<Integer, Doctor> doctors = new HashMap<Integer, Doctor>();
For each doctor I have some information such as in the class code (focus on the patients):
public class Doctor extends Person {
private int id;
private String specialization;
private List<Person> patients = new LinkedList<Person>();
My purpose is to write this function which return busy doctors: doctors that has a number of patients larger than the average.
/**
* returns the collection of doctors that has a number of patients larger than the average.
*/
Collection<Doctor> busyDoctors(){
Collection<Doctor> doctorsWithManyPatients =
doctors.values().stream()
.map( doctor -> doctor.getPatients() )
.filter( patientsList -> { return patientsList.size() >= AvgPatientsPerDoctor; })
.collect(Collectors.toList());
return null;
}
I want to use the streams as above to perform this operation. The problem is in collect method because at that point of usage doctorsWithManyPatients is of type List<Collection<Person>> and not Collection<Doctor>. How could I do that?
Assume that AvgPatientsPerDoctor is already defined somewhere.
You needn't use map (Doctor -> List<Person>), it will be used in the filter:
doctors
.values()
.stream()
.filter( d -> d.getPatients().size() >= AvgPatientsPerDoctor)
.collect(Collectors.toList());
For your case, map( doctor -> doctor.getPatients() ) returns Stream<List<Person>> and you should convert it to Stream<Doctor> again after filtering and before calling the collect method.
There is a different way that isn't the best one. Keep in mind that it changes the origin collection.
doctors.values().removeIf(d -> d.getPatients().size() < AvgPatientsPerDoctor);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With