简体   繁体   中英

double forEach stream over set and hashmap Java

I want to write a method that finds all employees (objects) from all projects that works more than 8 hours a day in a new set and that returns that set .

For this I already have a project class which holds a map of each employee as the key and the hours they work a day as a value.

In the class I'm writing the method in I have an set projects which contains all project objects.

Is it possible to use a functional interface / stream to:

  • iterate over the set of projects

  • then for each project iterates and filters (more than 8) over all the values in the map with employees in the project

  • return all the employees that work more than 8 hours per day in a set.

     public Set<Employee> getFulltimeEmployees() { Set<Employee> emp = projects.forEach(p -> p.getCommittedHoursPerDay().forEach()); return Set.of(); }

I have something like this, but I don't think this will work. projects is the set of all Project objects and getCommittedHoursPerDay() returns the map with the Employee object as the key and the hours of work per day as the value .

I would think the simplest way would be to use streams. The code below streams all projects and then maps to the entries in the map. It then filters all entries with hours > 8 and collects the keys in a set (which automatically removes duplicates).

projects.stream()
    .flatMap(p -> p.getCommittedHoursPerDay().entrySet().stream())
    .filter(e -> e.getValue() > 8)
    .map(Map.Entry::getKey)
    .collect(Collectors.toSet());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM