[英]Stuck with java8 lambda expression
我有Map<Integer,Doctor> docLib=new HashMap<>();
拯救Doctor
。
Class Doctor
有methods:getSpecialization()
返回一個String
,
getPatients(
)返回Person
類的集合。
在main方法中,我鍵入:
public Map<String,Set<Person>> getPatientsPerSpecialization(){
Map<String,Set<Person>> res=this.docLib.entrySet().stream().
map(d->d.getValue()).
collect(groupingBy(d->d.getSpecialization(),
d.getPatients()) //error
);
return res;
}
正如你所看到的,我有groupingBy
問題,我嘗試將相同的值d發送給方法,但這是錯誤的。 怎么解決這個?
您需要第二個收集器用於該映射 :
public Map<String,Set<Person>> getPatientsPerSpecialization(){
return this.docLib
.values()
.stream()
.collect(Colectors.groupingBy(Doctor::getSpecialization,
Collectors.mapping(Doctor::getPatients,toSet()))
);
}
編輯:
我認為我的原始答案可能是錯誤的(如果不能測試它很難說)。 由於Doctor::getPatients
返回一個Collection,我想我的代碼可能會返回Map<String,Set<Collection<Person>>>
而不是所需的Map<String,Set<Person>>
。
解決這個問題的最簡單方法是再次遍歷該Map
以生成所需的Map
:
public Map<String,Set<Person>> getPatientsPerSpecialization(){
return this.docLib
.values()
.stream()
.collect(Colectors.groupingBy(Doctor::getSpecialization,
Collectors.mapping(Doctor::getPatients,toSet()))
)
.entrySet()
.stream()
.collect (Collectors.toMap (e -> e.getKey(),
e -> e.getValue().stream().flatMap(c -> c.stream()).collect(Collectors.toSet()))
);
}
也許有一種方法可以通過單個Stream管道獲得相同的結果,但我現在無法看到它。
您可以使用toMap
代替groupingBy
:
public Map<String, Set<Person>> getPatientsPerSpecialization() {
return docLib.values()
.stream()
.collect(toMap(Doctor::getSpecialization,
d -> new HashSet<>(d.getPatients()),
(p1, p2) -> Stream.concat(p1.stream(), p2.stream()).collect(toSet())));
}
它的作用是將每個專業化的醫生分組,並將每個醫生映射到一組患者(所以Map<String, Set<Person>>
)。
如果,當從管道收集數據時,您遇到一個專業化的醫生,該醫生已經存儲為地圖中的一個關鍵字,您可以使用合並功能生成一組具有兩個集合的新值(已存儲的集合)作為鍵的值,以及要與鍵關聯的集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.