Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeMap with no unique key

Tags:

java

java-6

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 ?

like image 287
aleroot Avatar asked Dec 28 '22 19:12

aleroot


2 Answers

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.

like image 89
Stephen C Avatar answered Dec 30 '22 09:12

Stephen C


Check out the TreeMultimap class in the Google Guava library.

like image 33
Begui Avatar answered Dec 30 '22 09:12

Begui