Is there a clean (and null safe) way to multiply the values of a map in Java?

Omar Haque :

I have a Map<String, Double>, and want to multiply all the values in the map by 2, say, but keep the nulls as nulls.

I can obviously use a for loop to do this, but was wondering if there was a cleaner way to do so?

Map<String, Double> someMap = someMapFunction();
Map<String, Double> adjustedMap = new Hashmap<>();
if (someMap != null) {
    for (Map.Entry<String,Double> pair : someMap.entryset()) {
        if (pair.getValue() == null) {
            adjustedMap.put(pair.getKey(), pair.getValue());
        } else {
            adjustedMap.put(pair.getKey(), pair.getValue()*2)
        }

    }
}

Also sometimes the map returned by someMapFunction is an immutable map, so this can't be done in place using Map.replaceAll. I couldn't come up with a stream solution that was cleaner.

Eran :

My first instinct was to suggest a Stream of the input Map's entrySet which maps the values to new values and terminates with collectors.toMap().

Unfortunately, Collectors.toMap throws NullPointerException when the value mapper function returns null. Therefore it doesn't work with the null values of your input Map.

As an alternative, since you can't mutate your input Map, I suggest that you create a copy of it and then call replaceAll:

Map<String, Double> adjustedMap = new HashMap<>(someMap);
adjustedMap.replaceAll ((k,v) -> v != null ? 2*v : null);

Guess you like

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