2016-05-24 31 views
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已經在某處定義。

回答

4

你不必使用mapDoctor -> List<Person>),它將在filter使用:

doctors 
    .values() 
    .stream() 
    .filter(d -> d.getPatients().size() >= AvgPatientsPerDoctor) 
    .collect(Collectors.toList()); 

對於你的情況,map(doctor -> doctor.getPatients())返回Stream<List<Person>>,你應該後再filter ING和調用之前將其轉換爲Stream<Doctor>collect方法。


有一種不是最好的方法。請記住,它會更改原點集合。

doctors.values().removeIf(d -> d.getPatients().size() < AvgPatientsPerDoctor); 
+0

你說得對。我明白了。感謝您的答覆。如你所說,最終有辦法將它轉換成Stream ?這並不是真的需要,而只是爲了知道。 –

+1

@GiuseppeCanto,如果你有一個構造函數(或一個方法 - 命名爲'creator'),它接收到'List '並創建一個Doctor'類型的新對象 – Andrew

+1

@GiuseppeCanto,那麼你可以寫'map(this: :creator)'或'map(list - > this.creator(list))' – Andrew