Merging recusrive Hashmap in java 8

Viewed 53

I need to merge multiple HashMaps

map1:

{"41666":
 {"oyo_id":"KSD900",
 "contracted_rooms":null,
 "status":"live"
 },
 "41667":
 {"oyo_id":"JGH900",
 "contracted_rooms":null,
 "status":"live"
 }
}

map2:

{"41666":
 {"oyo_id":null,
 "contracted_rooms":31,
 "status":null
 },
 "41667":
 {"oyo_id":null,
 "contracted_rooms":3,
 "status":null
 }
}

Expected result

{"41666":
 {"oyo_id":"KSD900",
 "contracted_rooms":31,
 "status":"live"
 },
 "41667":
 {"oyo_id":"JGH900",
 "contracted_rooms":3,
 "status":"live"
 }
}

What I have tried:

AssignedPropertiesResponse:

@JsonProperty("oyo_id")
private String oyoId;

@JsonProperty("status")
private String status;

@JsonProperty("contractedRoomsCount")
private Double contracted_rooms_count;

AssignedPropertiesResponseList:

HashMap<String, AssignedPropertiesResponse>

map1.putAll(map2);

But this is overwriting values of map2 into map2.

2 Answers

Create a merge function

map2.merge(key, value, (v1, v2) -> new AssignedPropertiesResponse(v1.getOyoId(),v1.getStatus(),v2.getContractedRoomsCount())

and then you can iterate over the map2 and merge the entries into map1

map2.forEach(
  (key, value) -> map1.merge(key, value, (v1, v2) -> new AssignedPropertiesResponse(v1.getOyoId(),v1.getStatus(),v2.getContractedRoomsCount())));

Here is an exemplary implementation:

map2.forEach((key, value) -> {
    AssignedPropertiesResponse r = map1.get(key);
    if(r != null) r.setContracted_rooms_count(value.getContracted_rooms_count());
});

P.S.: Variables names are written with camelCase in java.

Related