Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate key in TreeMap [closed]

Tags:

java

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?

like image 895
Vivek Dhiman Avatar asked Feb 13 '14 09:02

Vivek Dhiman


People also ask

What happens when duplicate key is added to TreeMap?

A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.

What happens if you add duplicate key to map?

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.

Is duplicate key allowed in 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.

How do you prevent duplicates in maps?

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.


2 Answers

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.

like image 72
Tim B Avatar answered Oct 18 '22 15:10

Tim B


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.

like image 33
Abimaran Kugathasan Avatar answered Oct 18 '22 16:10

Abimaran Kugathasan