Reputation: 49
List<String> list = hmap.getOrDefault(key,new ArrayList<String>());
list.add(s);
hmap.put(key,list);
Why do I need to use hmap.put method again?
My understanding is this.
Assume there is no existing key value pair. So, with
List<String> list = hmap.getOrDefault(key,new ArrayList<String>());
I am mapping key with a new instance of the ArrayList.
If I then add a string to the same instance then the hashmap also should get updated automatically right? key => List Object. If I add to the list object then the object reference should not change right?
Why do I need to again use the put method and do this?
hmap.put(key,list);
Upvotes: 3
Views: 1108
Reputation: 159145
Read the documentation, i.e. the javadoc of getOrDefault()
:
Returns the value to which the specified key is mapped, or
defaultValue
if this map contains no mapping for the key.
It says nothing about inserting the default value if the key is not found.
So if the key is not found, it does return that new list and you add an element to it, but you also need to put()
that new list into the map. If the key was found, then put'ing it again doesn't hurt (except for performance).
However, the correct way to do this is to use computeIfAbsent()
, for 2 reasons:
It will put the new list for you.
If the key exists, it will not create an list just to throw it away again.
hmap.computeIfAbsent(key, k -> new ArrayList<>())
.add(s);
Upvotes: 12
Reputation: 60036
To make it in one shot you have to use computeIfAbsent
:
hmap.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
Upvotes: 3
Reputation: 363
You want to use HashMap.computeIfAbsent
. getOrDefault
just gets the value if it exists, otherwise it returns the default, without adding it.
See https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function- and https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-
Upvotes: 5