Java8 introduced those nice methods getOrDefault()
and putIfAbsent()
, allowing to write code like:
Map<Foo, List<Bar>> itemsByFoo = ...
List<Bar> bars = itemsByFoo.getOrDefault(key, new ArrayList<>());
bars.add(someNewBar);
Now I am wondering if there are good factual reasons to either do:
itemsByFoo.put(key, bars);
or
itemsByFoo.putIfAbsent(key, bars);
Both would work:
- option 1 might do a lot of unnecessary "put" calls when adding elements to lists happens often
- option2 might do a lot of unnecessary "containsKey" calls when adding new entries for new keys is dominant
SO: are the good reasons to go for option 1 or option 2 "always"?
See Question&Answers more detail:os