坚持使用java8 lambda表达式

时间:2015-06-20 05:15:41

标签: java lambda java-8

我有deque<float> move1(deque<float>p, int u) { deque<float> q; for(int i=0; i<p.size(); i++) q.push_back(p[(i-u) % p.size()]); return q; } 来保存Map<Integer,Doctor> docLib=new HashMap<>();的等级。

Doctor Class Doctor返回methods:getSpecialization()
String)返回类getPatients(的集合。

在main方法中,我输入:

Person

正如您所看到的,我对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; } 有疑问,我尝试将相同的值d发送给方法,但这是错误的。 怎么解决这个问题?

2 个答案:

答案 0 :(得分:5)

您需要第二个收藏家mapping

public Map<String,Set<Person>> getPatientsPerSpecialization(){
    return this.docLib
               .values()
               .stream()
               .collect(Colectors.groupingBy(Doctor::getSpecialization,
                                             Collectors.mapping(Doctor::getPatients,toSet()))
                       );
}

编辑:

我认为我的原始答案可能是错误的(如果不能测试它很难说)。由于Doctor::getPatients会返回一个集合,因此我认为我的代码可能会返回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管道获得相同的结果,但我现在无法看到它。

答案 1 :(得分:2)

而不是groupingBy,您可以使用toMap

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>>)。

如果,当从管道收集数据时,您遇到一位已经作为关键字存储在地图中的专业医生,您可以使用合并功能生成一组具有两组的新值(设置为已存储为键的值,以及要与键关联的集合。