Is it useful to check Map.containsKey () first before trying to remove the value from the map?
No, this is counterproductive:
- In case the item is missing, you will not see the difference
- In case the item is there, you will get two kinds of search.
If you want to correctly delete an element, just call map.remove(key) .
The same question is about getting values
The same logic applies here. Of course, you need to check the result for null , so in this case if will stay there.
Note that this cleaning exercise begins with readability, and only then about performance. Access to the card is a quick operation, so accessing it twice is unlikely to cause serious performance problems, except in some fairly extreme cases. However, removing additional conditional code will make your code more readable, which is very important.
source share