I'm wondering, does it make any sense to check for a particular key before trying to access it. Example:
Map myMap ....
if myMap.containsKey(key) {
Object value = myMap.get(key);
.....
}
Example of not using containsKey
:
Object value = myMap.get(key);
if (value != null) {
......
}
EDIT: to clarify on null keys and values. Let's say, that map doesn't allow null keys and null values, so this two examples be identical.
Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not. HashMap allows null values and null keys. Both HashSet and HashMap are not synchronized.
If you have to avoid duplicates you also know we have to use Set from the collections. You can do like Map<set<id>,sObject> newMap = Map<set<id>,sObject>(); Please take it as a general solution which you can modify as per your requirement.
Multimaps allow for multiple keys by maintaining a collection of values per key, i.e. you can put a single object into the map, but you retrieve a collection.
Keys are unique once added to the HashMap , but you can know if the next one you are going to add is already present by querying the hash map with containsKey(..) or get(..) method.
Yes - keys can have null
values:
Map myMap = ...;
myMap.put("foo", null);
if (myMap.containsKey("foo")) {
Object value = myMap.get(key); // value is null
}
Object value = myMap.get("foo");
if (value != null) {
// you won't get here
}
You could argue (and I'd agree) that not distinguishing a null
value from a non-existent entry was a pretty bad design decision when they first made Java's collection API.
(Some maps - Hashtable
and ConcurrentHashMap
, at least - don't allow null
values, which makes containsKey
less important there, but it's still a nice readability improvement over m.get(k) == null
.)
In case your map allows for null
values, with just get(key)
you can't differentiate between key/value pair that has value = null
and "no matching key/value pair exists".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With