Ronny Giezen
Ronny Giezen

Reputation: 645

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:

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.

Upvotes: 0

Views: 43

Answers (1)

sprinter
sprinter

Reputation: 27956

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

Upvotes: 2

Related Questions