Put in the map if key exists and value is not null, else throw exception

Harshal Parekh :
void addToMapIfKeyExists(String k, String v) {
    if (!map.containsKey(k)) {
        throw new NoSuchElementException(k + " does not exist in the map");
    }

    // else ignore
    if (v != null) {
        map.put(k, v);
    }
}

Can I write this in a better way in Java 8? Can I merge it into one expression in some way?

rzwitserloot :

You can, in a single statement:

public void overwrite(String k, String v) {
    map.compute(k, (key, value) -> {
        if (value == null) throw new NoSuchElementException(key + " does not exist in the map");
        return v == null ? value : v;
    });
}

The above does:

[1] if key is not in the map, or is mapped to null, it throws NoSuchElementException.

[2] Otherwise, will do nothing if you're trying to set null.

[3] otherwise, will set the key to the new value

Which is apparently what you want, but that's a bizarre combination of requirements.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360934&siteId=1