[英]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.