Tango12
Tango12

Reputation: 3

How to apply double filter in java streams?

I have an Employee class having salary and department and a employee list.

static class Employee {
    private String department;
    private int salary;

    //getters
    getDeparment()
    getSalary()
}

List<Employee>

I need to find the number of departments with minimum 30 employees having paid minimum of 100 as salary.

So far I have got this which gives me number of employees per department. But I'm not sure how to apply the filters.

HashMap<String, Long> collect = employees
            .stream()
            .collect(Collectors.groupingBy(Employee::getDepartment, HashMap::new, Collectors.counting()));

Any help would be appreciated.

Upvotes: 0

Views: 747

Answers (2)

Jo&#227;o Dias
Jo&#227;o Dias

Reputation: 17460

The following should do the trick:

Set<String> departments = employees.stream()
        .filter(employee -> employee.getSalary() >= 100)
        .collect(Collectors.groupingBy(Employee::getDepartment, HashMap::new, Collectors.counting()))
        .entrySet().stream().filter(entry -> entry.getValue() >= 30)
        .map(Map.Entry::getKey)
        .collect(Collectors.toSet());

You start by filtering out the employees that have a salary of less than 100. Then you group the employees by department and count the number of employees in the department. Finally, you need to filter out all departments that have less than 30 employees and map the final result to a Set.

Upvotes: 3

Vojin Purić
Vojin Purić

Reputation: 2376

  HashMap<String, Long> collect = employees
                .stream()
                .filter(e-> e.getSalary() >= 100 && e.getDeparment().getEmployees().size >= 30)

I don't know your getters but you get the point. In the end just collect it to map

Upvotes: 1

Related Questions