Duplicate key in TreeMap [closed]
All maps share the same basic properties, one of which is that all keys must be unique. Hence why keySet()
returns a Set
.
To do what you are looking for you need a Multimap - which is essentially a Map to a List.
Map<Integer, List<String>> multiMap;
To add an object get the list for that key, if it is null add a list then add your value to the list, otherwise just add your value to the existing list.
There are some multimap implementation available in various 3rd party libraries or it's easy enough to implement your own.
TreeMap#public V put(K key, V value)
API says
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.