How does java.util.Map’s getOrDefault() work?

Shouldn’t the default object be created only if it is not there in the map ?

How could that be the case? This call:

map.getOrDefault("1", new Empl("dumnba"))

is equivalent to:

String arg0 = "1";
Empl arg1 = new Empl("dumnba");
map.getOrDefault(arg0, arg1);

In other words, all arguments are evaluated before being passed to the method.

You could potentially use computeIfAbsent instead, but that will modify the map if the key was absent, which you may not want:

System.out.println(map.computeIfAbsent("1", k -> new Empl("dumnba")));

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)