I noticed that if I do map.getOrDefault(\"key1\", new Object()), even if object is present for key1
in the map, new Object()
is created. Though it is n
All the arguments to a function are evaluated before the function is executed. Java needs to evaluate new Empl("dumnba")
so it can pass the result into getOrDefault
. It can't know before getOrDefault
is called that one of the arguments is not going to be required.
If you want to provide a default that is not computed unless needed, you can use computeIfAbsent. For this, you pass in a function, and that function is only executed if the default value is required.
map.computeIfAbsent("1", key -> new Empl("dumnba"))