简体   繁体   中英

Java TreeMap not good enough

I want to have a Map<Integer, String> that can be sorted out. I have tried to use a TreeMap<Integer, String> but it only stores one key per element and I want to have multiple same key elements.
For example, when I add:

map.put(1, "Daniel");
map.put(3, "Monica");
map.put(4, "Pinto");
map.put(3, "Lucia");

and then print all elements, with the TreeMap it appears as:

1 Daniel
3 Lucia
4 Pinto

and I want it to print:

1 Daniel
3 Monica
3 Lucia
4 Pinto

what datatype should I use for this?

Keys in a map are unique, so you can associate only one value with each key. That's why your key "3" appears only once in the output.

There seem to be two solutions, depending on what your requirements are:

  • Use a SortedSet , using elements compound of an Integer and a String with a custom Comparator . That way, "3 Monica" and "3 Lucia" would form completely independent elements of your collection. It would match your output in that each element in the collection would be one row in the output shown in your question, but feels kind of clumsy and is most likely not exactly what you want.
  • Use a collection class for your values in the map, eg a List<String> , so you would have a Map<Integer,List<String>> . Then, you cannot use the put method to add to that list, but you need to make your own method to lazily retrieve or create the List , and append the new element. The collection would then rather look like this:

    1, [Daniel]
    3, [Monica, Lucia]
    4, [Pinto]

and thus would not match exactly what you asked for but is more likely what you want.

Use MultiMap - a map that holds a collection of values against each key.

MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);

coll will be a collection containing "A", "B", "C".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM