Issue
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?
Solution
Method getOrDefault()
evaluates both arguments before executing its logic.
If you want to provide an optional part that will be evaluated lazily, than 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 lambda expression will not be executed.
Answered By - Alexander Ivanchenko
Answer Checked By - Gilberto Lyons (JavaFixing Admin)