3
我有一個醫生集合(作爲散列表)到一個通用醫院類中。.collect(Collectors.toList())和Java上的流方法
Map<Integer, Doctor> doctors = new HashMap<Integer, Doctor>();
對於每一個醫生,我有一些信息,比如在類代碼(側重於患者):
public class Doctor extends Person {
private int id;
private String specialization;
private List<Person> patients = new LinkedList<Person>();
我的目的是寫這個函數返回忙醫生:醫生,有一個患者數量大於平均數。
/**
* 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;
}
我想使用上述流來執行此操作。問題出在collect
方法中,因爲在該使用點doctorsWithManyPatients
的類型是List<Collection<Person>>
而不是Collection<Doctor>
。我怎麼能這樣做?
假設AvgPatientsPerDoctor
已經在某處定義。
你說得對。我明白了。感謝您的答覆。如你所說,最終有辦法將它轉換成Stream?這並不是真的需要,而只是爲了知道。 –
@GiuseppeCanto,如果你有一個構造函數(或一個方法 - 命名爲'creator'),它接收到'List'並創建一個Doctor'類型的新對象 –
Andrew
@GiuseppeCanto,那麼你可以寫'map(this: :creator)'或'map(list - > this.creator(list))' – Andrew