Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to existing map with Java stream

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**));
like image 467
Neo Avatar asked Oct 27 '25 09:10

Neo


1 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()));
like image 71
Eran Avatar answered Oct 29 '25 22:10

Eran