Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

java - Should I use put() or putIfAbsent() after using getOrDefault()?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getOrDefault is suitable if you want to use a stand-in for an absent value without modifying the map. If you want to add a new value for absent keys, you can do it right in one operation.

List<Bar> bars = itemsByFoo.computeIfAbsent(key, x -> new ArrayList<>());
bars.add(someNewBar);

or even

itemsByFoo.computeIfAbsent(key, x -> new ArrayList<>()).add(someNewBar);

In the best case, when being overridden by the Map implementation, like with HashMap, this will bear a single hash lookup only.

Not that putIfAbsent only bears two lookups when using the default implementation, but, of course, most Map implementations will provide a single lookup implementation for it. Still, the combination of getOrDefault and putIfAbsent would still bear two lookups in the best case, whereas an optimized computeIfAbsent does only one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...