The remove(key, value) method removes the entry for key if it is currently mapped to value . This method was added in Java 1.8. Javadoc for the Map interface mentions the following default implementation:
if (map.containsKey(key) && Objects.equals(map.get(key), value)) { map.put(key, newValue); return true; } else return false;
Since the Objects class was added only in Java 1.7, for Java 1.6 you need to write an equality test yourself. So, if you do not need the return value of the method, you can replace map.remove(key, value) with:
if (map.containsKey(key) { Object storedValue = map.get(key); if (storedValue == null ? value == null : storedValue.equals(value)) { map.remove(key); } }
Please note that this is not thread safe. If you access the map from multiple threads, you will need to add a synchronized block.
source share