Nested Hashmap: Alternative to putIfAbsent which does not requires null check and manual get?

1.5k Views Asked by At

I have a nested HashMap looking like this: HashMap<String, HashMap<String,Object>>.

I created a add method to fill the HashMap

private void add(String currentVersion, String targetVersion, Object object) {
    HashMap <String, HashMap <String, Object >> nestedMap = definedUpdatePlans.putIfAbsent(currentVersion, new HashMap());
    if (nestedMap == null) {
        nestedMap = definedUpdatePlans.get(currentVersion);
    }
    nestedMap.put(targetVersion, object);
}

As you see, I'll add the nested map if absent. If it was already present, I'll get the current value as return value. In case if it was absent, putIfAbsent returns null which requires me to do a null check and a manual get to populate the variable.

This seems not very clean, but I wouldn't know a better way.

Is there a way to add a value if not existing and keep working with the new or pre existing value in a more fluent way?

1

There are 1 best solutions below

1
On BEST ANSWER

Use computeIfAbsent:

private void add(String currentVersion, String targetVersion, Object object) {
    definedUpdatePlans.computeIfAbsent(currentVersion, k -> new HashMap())
                      .put(targetVersion, object);
}

It returns:

the current (existing or computed) value associated with the specified key, or null if the computed value is null