如何从过滤后的流中的多个地图中收集键集?

How to gather a keyset from multiple maps from a stream that is filtered?

我正在尝试学习使用流和收集器,我知道如何使用多个 for 循环,但我想成为一个更高效的程序员。

每个项目都有一个映射 committedHoursPerDay,其中键是员工,值是以整数表示的小时数。我想遍历所有项目的 committedHoursPerDay 映射并过滤 committedHoursPerDay 超过 7(全职)的映射,并将每个全职工作的员工添加到集合中。

到目前为止我写的代码是这样的:

    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();
    }

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

这里有一对多的概念。您可以先使用 flatMap 展平地图,然后将 filter 应用于地图条目。

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步骤returns一个Stream<Map.Entry<Employee, Integer>>filter 因此在 Map.Entry<Employee, Integer>.

上运行

您还可以在收集步骤中使用方法参考,如 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))