Megre two maps of dfferent object type into one with completing object value in map1

Viewed 46

is it possible to merge two maps with the same keys but different object and finnaly get map completed of data from second map?

public class Employee {
private String firstName;
private String lastName;
private Address address;
}

public class Address {
private String city;
private String country;
private String street;
}


Map<String, Employee> map1 = new HashMap<>();
Map<String, Address> map2 = new HashMap<>();

//We need map 3 with value in employee completed with address.

Map<String, Employee> map3 = new HashMap<>();
2 Answers

if the keys are the same you can easily merge two maps. If you have the maps in your code like you mentioned the following code should work just fine.

map1.keySet().stream().forEach(key -> {
    Employee employee = map1.get(key);
    employee.address = map2.get(key);
    map3.put(key, employee);
});

Assuming Employee class has a setter method for address you can do:

map1.forEach((key, employee) -> employee.setAddress(map2.get(key)));

If you need to instantiate a new Map:

private Employee setAddress(Map.Entry<String, Employee> entry) {
    Employee employee = entry.getValue();
    return new Employee(employee.getFirstName(), employee.getLastName(), 
            map2.get(entry.getKey()));
}

Then you can do:

Map<String, Employee> map3 = map1.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, this::setAddress));
Related