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

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

look in the java 8 implementation:

default V getOrDefault(Object key, V defaultValue) {
    V v;
    return (((v = get(key)) != null) || containsKey(key))
        ? v
        : defaultValue;
}

the doc specifies:

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. ault

it will return the default is not present in the map

example:

    Map<String, String> map = new HashMap<>();

    map.put("1", "Foo");
    //search for the entry with key==1, since present, returns foo
    System.out.println(map.getOrDefault("1", "dumnba"));
    //search for the entry with key==2, since not present, returns dumnba
    System.out.println(map.getOrDefault("2", "dumnba"));

Tags:

Java