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

Nuñ*_*ada 5 java collections hashmap java-8

我有这段代码:

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

我想知道是否有可能使用Jav8增强功能重构它compute(),computeIfPresent()或者computeIfAbsent()

And*_*ner 6

假设value非null,则不需要使用条件或任何这些compute*方法.

ValueType oldValue = map.put(key, value);
return value.equals(oldValue);
Run Code Online (Sandbox Code Playgroud)

  • 在对象具有身份的情况下,也就是说:总是.也许这在OP的背景下并不重要,但我认为在你的回答中值得一提. (4认同)