HashMap override value only if value for particular key is null/empty/"None"

Viewed 96

I am stuck with a HashMap issue. I am trying to copy data from one HashMap to another.

Please excuse my syntax - this is just an example. I also tried looking at other examples but could not find anything for my usecase.

Lets say -

HashMap<String, String> hashMap1 = {(1, "New Value"), (2, "New Value")}    
HashMap<String, String> finalHashMap = {(1, "None"), (2, "Blah"), (3, "Something else")}

This is the original code:

hashMap1.forEach(finalHashMap::putIfAbsent);

This is final output I want:

finalHashMap = {(1, "New Value"), (2, "Blah"), (3, "Something else")}

Note: 2 does not get overwritten because its value is not "None"

This works when Null or Empty case but not for None case :(

Can someone help me and modify code to help with "None" case as well?

I can do this traditional way, but trying to see if there is any one liner that I can use for this.

2 Answers

Try it like this. For each value in the hashMap1 that meets your condition in finalHashMap, replace it with the value for the same key in hashMap1. It's important to first check for a null value so future tests won't throw an NPE.

hashMap1.forEach((k, v) -> { String value = finalHashMap.get(k);
    if (value == null || value.equals("None") || value.isEmpty()) {
        finalHashMap.put(k, hashMap1.get(k));
    }
});

System.out.println(finalHashMap);

prints

{1=New Value, 2=Blah, 3=Something else}

You can use Collectors.toMap and check the collisions:

Map<String, String> merged = 
    Stream.concat(finalHashMap.entrySet().stream(), hashMap1.entrySet().stream())
          .collect(toMap(Map.Entry::getKey, Map.Entry::getValue,
                         (a, b) -> (a == null || a.isEmpty() || "None".equals(a)) ? b : a));
Related