I hope all is good for you.
I have two maps and I want to keep null values. I know that merge function can't manage null values but I need to keep null data and use the Binary Operation.
How I can manage my code to avoid NPE.
private Map<String, Object> mergeMaps(
Map<String, Object> map1, Map<String, Object> map2) {
return Stream.of(map1, map2)
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> v1 != null
&& StringUtils.isNotEmpty(v1.toString())
? v1
: v2
));
}
Sample test code:
public static void main(String[] args) {
Map<String, Object> map1 = new HashMap<>();
map1.put("k1", null);
map1.put("k2", "2");
map1.put("k3", null);
Map<String, Object> map2 = new HashMap<>();
map2.put("k1", "1");
map2.put("k2", null);
map2.put("k3", null);
var result = mergeMaps(map1, map2);
System.out.println(result);
}
should output something like {k1=1, k2=2, k3=null}
; k1 having been replaced by map2, k2 staying from map1, and k3 being null
in both.
Thanks a lot.
I'd go for
Map<String, Object> mergeMaps(Map<String, Object> map1,
Map<String, Object> map2) {
Map<String, Object> result = new HashMap<>(map1);
map2.forEach((k, v) -> {
var value = result.get(k);
if (value == null || value.toString().isEmpty()) {
result.put(k, v);
}
});
return result;
}
Which runs fine for the test case.