Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Map.containsKey() useful? [duplicate]

Tags:

java

map

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.

like image 298
dhblah Avatar asked May 06 '13 12:05

dhblah


People also ask

Does map take duplicate values?

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.

How do you prevent duplicates in maps?

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.

Which map will allow duplicate keys?

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.

How can I tell if a map has duplicate keys?

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.


2 Answers

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.)

like image 66
gustafc Avatar answered Oct 21 '22 02:10

gustafc


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".

like image 26
vertti Avatar answered Oct 21 '22 02:10

vertti