java usage of parallelStream resulting into map

70 views Asked by At

I have a single threaded code as follows :

private Map<Employee, EmployeeDeptMap> empToEmpDept(List<Employee> empList) {
    Map<Employee, EmployeeDeptMap> map = new HashMap<>();
    for (Employee emp : empList) {
        map.put(emp, empDepartmentResolver.resolve(emp));
    }
    return map;
}

Here the code is sequentially traversing over the employee list and mapping department for each employee on basis of some rules which are abstract defined.

The requirement here is I want to run it in parallel so that multiple department resolution can happen in parallel and save time.

The list is quite big in size.

I tried with following piece of code but got stuck in applying the parallelism there

empList.parallelStream()
       .map(emp-> empDepartmentResolver.resolve(emp))
       .collect(Collectors.toMap())

Any suggestions what will be best way here to resolve them in parallel.

1

There are 1 answers

2
Plus On

As @Abra mentioned, you need to pass parameters to define how the Map should be created. You could try this code below:

Map<Employee, EmployeeDeptMap> map = empList
        .parallelStream()
        .collect(Collectors.toMap(Function.identity(), empDepartmentResolver::resolve));