Search code examples
javasortedmap

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?


Solution

  • 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, e.g. 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.