如何在Java中具有多图功能? [英] How to have multimap functionality in Java?
问题描述
I want to have the functionality of MultiMap in Java, providing the same functionality as that of cpp MultiMap so that I am able to have multiple keys with the same value. Multiple elements in the container can have equivalent keys. I thought this will work :
TreeMap<Key, TreeMap<Key, Value> >.
感谢您的帮助.
推荐答案
如果您想要一致的语义,则必须自己动手.实现它的最简单方法是通过Map<K, List<V>>
对其进行备份.这样,您可以将一个键映射到多个值.
If you want consistent semantics, you would have to roll your own. The easiest way to implement it would be to back it by a Map<K, List<V>>
. This way you can map one key to multiple values.
但是,关于语义,您需要考虑一些事项.例如,假设您具有以下多重地图:
However, there are some things you need to consider regarding semantics. For example, assume you have the following multimap:
a -> [1, 2, 3]
b -> [4, 5]
以上内容的大小将报告为2,但如果您认为Map可以表示为5,则也可以解释为5:
The size of the above will be reported as 2, but could be interpreted as 5 also, if you consider that the Map can be represented as so:
a -> 1
a -> 2
a -> 3
b -> 4
b -> 5
这也与您返回的值有关.返回[1, 2, 3, 4, 5]
而不是[[1, 2, 3], [4, 5]]
更有意义.这也适用于条目集;您可能要返回上面显示的对.
This has implications for the values that you return as well. It would make more sense to return [1, 2, 3, 4, 5]
and not [[1, 2, 3], [4, 5]]
. This would also apply to the entry set; you may want to return pairs as displayed above.
因此,可能的实现方式是实现Map<K, V>
并使用支持Map<K, List<V>>
.然后,您必须在遵守多图语义的同时实现各种方法.
Hence a possible implementation would be to implement Map<K, V>
and use a backing Map<K, List<V>>
. You would then have to implement the various methods while adhering to the multimap semantic.
如果您不关心语义,而只希望将单个键映射到多个值,则可以直接使用Map<K, List<V>>
仍然可以得到所需的内容.
If you don't care about the semantics but just want an ability to map a single key to multiple values, you can just use a Map<K, List<V>>
directly and still get what you need.
这篇关于如何在Java中具有多图功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!