Home > Software engineering >  How to apply double filter in java streams?
How to apply double filter in java streams?

Time:11-19

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.

CodePudding user response:

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.

CodePudding user response:

  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

  • Related