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> >.
Any help is appreciated.
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]
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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With