Search code examples
javajava-6

TreeMap with no unique key


I use a TreeMap class for store messages information with their priority in my application. I've used a treeMap class for do it because this class order automatically the element based on the key value, for example i have this situation :

enum Priority { HIGH, MEDIUM, LOW }
TreeMap<Priority,String> tMap = new TreeMap<Priority,String>();

I use the key (priority of the message) for automatically order messages based on the priority severity, but the problem is that in TreeMap the key is unique then if i try to insert two messages with the same priority the first is overwritten ....

How can i change this behaviour and disable unique constraint on TreeMap?

Is there a class like TreeMap that allow to put the same Key for multiple element ?


Solution

  • How can i change this behaviour and disable unique constraint on TreeMap?

    You can't. The uniqueness of keys is a fundamental invariant of the Map interface.

    Is there a class like TreeMap that allow to put the same Key for multiple element ?

    You can implement this as a Map<Priority,List<String>> and manage the lists yourself. This is a good option if (for example) you want to process the messages for a given priority in fifo order.

    Alternatively, you can use a MultiMap class; e.g. from Apache commons collections or Guava.