Java 8的compute()和computeIfPresent()来检查一个现有的值

时间:2018-10-21 19:47:36

标签: java collections java-8 hashmap

我有这段代码:

if (notificationSend.get(key) != null && notificationSend.get(key).equals(value)) {
   return true;
} else {
   notificationSend.put(key, value);
   return false;
}

我想知道是否可以使用compute()computeIfPresent()computeIfAbsent()之类的Jav8增强功能来重构它

1 个答案:

答案 0 :(得分:6)

假设value不为空,则无需使用条件方法或任何compute*方法。

ValueType oldValue = map.put(key, value);
return value.equals(oldValue);