I have the below code for tree map where I store duplicate key and it seems overwrite the existing one.
TreeMap<String, Integer> tm=new TreeMap<>();
tm.put("vivek", 1);
tm.put("vivek", 2);
System.out.println(tm);
It prints {vivek=2}
So it means map allow to overwrite on key basis?
A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.
Overview. The map implementations provided by the Java JDK don't allow duplicate keys. If we try to insert an entry with a key that exists, the map will simply overwrite the previous entry. In this article, we'll explore a collection type that allows duplicate keys in a map.
Duplicate keys are not allowed in a Map. Basically, Map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains an order of the objects but HashMap will not. HashMap allows null values and null keys.
If you have to avoid duplicates you also know we have to use Set from the collections. You can do like Map<set<id>,sObject> newMap = Map<set<id>,sObject>(); Please take it as a general solution which you can modify as per your requirement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With