Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> >. 

Any help is appreciated.

like image 940
rt56 Avatar asked Oct 18 '25 19:10

rt56


1 Answers

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.

like image 153
Vivin Paliath Avatar answered Oct 21 '25 11:10

Vivin Paliath