java—如何从经过过滤的流中的多个Map中收集密钥集?

deyfvvtc  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(288)

我正在努力学习使用流和收集器,我知道如何使用多个for循环,但我想成为一个更高效的程序员。
每个项目都有一个MapCommittedHoursPerday,其中键是employee,值是用整数表示的小时数。我想遍历所有项目的committedhoursperdayMap,过滤committedhoursperday大于7(fulltime)的Map,并将每个全职工作的员工添加到集合中。
到目前为止,我编写的代码是:

public Set<Employee> getFulltimeEmployees() {
        // TODO
        Map<Employee,Integer> fulltimeEmployees = projects.stream().filter(p -> p.getCommittedHoursPerDay().entrySet()
                .stream()
                .filter(map -> map.getValue() >= 8)
                .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())));

        return fulltimeEmployees.keySet();
    }

但是,过滤器识别Map,因为我可以访问键和值,但是在.collect(collectors.tomap())中,它不识别Map,只将其视为lambda参数

kxeu7u2r

kxeu7u2r1#

这里有一对多的概念。首先可以使用 flatMap 然后申请 filter 到Map条目。

Map<Employee,Integer> fulltimeEmployees = projects.stream()
                .flatMap(p -> p.getCommittedHoursPerDay()
                        .entrySet()
                        .stream())
                .filter(mapEntry  -> mapEntry.getValue() >= 8)
                .collect(Collectors.toMap(mapEntry -> mapEntry.getKey(), mapEntry -> mapEntry.getValue()));

这个 flatMap 步骤返回一个 Stream<Map.Entry<Employee, Integer>> . 这个 filter 因此在一个 Map.Entry<Employee, Integer> .
也可以在collect步骤上使用方法引用 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))

相关问题