Adding to existing map with Java stream

Viewed 985
Map<Long, Employee.status> prevStatus = empRecords.stream()
      .collect(Collectors.toMap(employeeRecord::getEmloyeeID,
                                employeeRecord::getEmployeeStatus));

I already have the above code, I need to add a similar operation but instead of creating a new Map I want to add the result to the existing map.

prevStatus = empRecords.stream()
      .collect(Collectors.**toMap**(employeeRecord::getEmloyeeID,
                                    employeeRecord::**getUSEmployeeStatus**));
2 Answers

You can create a new Map and add its entries to the existing Map:

prevStatus.putAll(
    empRecords.stream()
              .collect(Collectors.toMap(employeeRecord::getEmloyeeID,
                                        employeeRecord::getUSEmployeeStatus)));

Or you can use forEach instead of collect:

empRecords.stream()
          .forEach(emp -> prevStatus.put(emp.getEmloyeeID (),
                                         emp.getEmployeeStatus()));

This is expected code

empRecords.stream()
                  .collect(Collectors.toMap(employeeRecord::getEmloyeeID,
                                            employeeRecord::getEmployeeStatus,(newVal,oldVal)->newVal,()->existingMap));

Where (newVal,oldVal)->newVal logic is for what if key is already present in existing Map and existingMap is your existing map. Make sure existingMap is not null. If it is null going with new HashMap what you shared in your code itself fine.

Related