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.

Leave a Comment