Java Map implementation that returns a default value instead of null

前端 未结 6 875
萌比男神i
萌比男神i 2020-12-14 06:27

I have a Map> in my code, where I\'d avoid potential null pointers if the map\'s #get() method returned an empty l

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 07:32

    @Jon's answer is a good way to do what you are asking directly.

    But is strikes me that what you might be trying to implement is a "multimap"; i.e. a mapping from a key to a collection of values. If that is the case, then you should also look at the multimap classes in Guava or Apache commons collections.

    Look at:

    • the com.google.common.collect.Multimap interface and its implementations, or
    • the org.apache.commons.collections.MultiMap interface and its implementations.
    • the org.apache.commons.collections4.MultiMap interface and its implementations (a new version of the previous MultiMap; introduced in v4).

提交回复
热议问题