3
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);
2
  • 1
    This assumption is wrong : I am mapping key with a new instance of the ArrayList..
    – jrook
    Dec 30, 2019 at 20:20
  • 3
    I think the name of the method getOrDefault is pretty clear about not putting anything anywhere.
    – f1sh
    Dec 30, 2019 at 20:24

3 Answers 3

12

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);
5

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-

3

To make it in one shot you have to use computeIfAbsent :

hmap.computeIfAbsent(key, k -> new ArrayList<>()).add(s);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.