Reputation: 1116
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?
Upvotes: 0
Views: 109
Reputation: 1196
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:
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.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]
Upvotes: 2
Reputation: 580
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".
Upvotes: 1