Why putting method as param of getOrDefault, the method will be invoked anyway?

Viewed 108
Map<String, Integer> iMap = new HashMap<>();
iMap.put("a", 1);
Integer a = iMap.getOrDefault("a", getNum());

private Integer getNum() {
    System.out.println("getNum Method has been invoked");
    return 123;
}

output: getNum Method has been invoked

the iMap has key "a", why getNum still has been invoked?

1 Answers

Method getOrDefault() evaluates both arguments before executing its logic.

If you want to provide an optional part that will be evaluated lazily, then you need Java-8 methods like merge() or computeIfAbsent().

Map<String, Integer> iMap = new HashMap<>();
iMap.put("a", 1);
Integer a = iMap.computeIfAbsent("a", key -> getNum());

Since key "a" is present in the map, the lambda expression will not be executed.

Note:

  • computeIfAbsent() isn't a uniform substitution for getOrDefault(). These methods are meant to represent different operations on a map. By its nature, computeIfAbsent() is closer to put() or putIfAbsent() rather than to getOrDefault(). The main goal of computeIfAbsent() is to make changes in a map, while the main goal of getOrDefault() is to retrieve a value.
Related