I want to have a map with duplicate keys.
I know there are many map implementations (Eclipse shows me about 50), so I bet there must be one that allows this. I know it's easy to write your own map that does this, but I would rather use some existing solution.
Maybe something in commons-collections or google-collections?
We don't need to depend on the Google Collections external library. You can simply implement the following Map:
Please make sure to fine tune the code.
just to be complete, Apache Commons Collections also has a MultiMap. The downside of course is that Apache Commons does not use Generics.
This problem can be solved with a list of map entry
List<Map.Entry<K,V>>
. We don't need to use neither external libraries nor new implementation of Map. A map entry can be created like this:Map.Entry<String, Integer> entry = new AbstractMap.SimpleEntry<String, Integer>("key", 1);
If there are duplicate keys then a key may correspond to more than one value. The obvious solution is to map the key to a list of these values.
For example in Python:
With a bit hack you can use HashSet with duplicate keys. WARNING: this is heavily HashSet implementation dependant.