Duplicates in LinkedHashMap

Ramin picture Ramin · Nov 8, 2013 · Viewed 19k times · Source

In my code I am using a set of interleaved LinkedHashMaps inside each other as below. The code is fine and gives me the result I want except it automatically removes the duplicates. I couldnt find out how I can use TreeMap or Set in order to keep the duplicates.

LinkedHashMap<String, LinkedHashMap<Integer, LinkedHashMap<String, Vector<String>>>> 
dataAll =new LinkedHashMap<String, LinkedHashMap<Integer, LinkedHashMap<String, 
Vector<String>>>>();

Answer

KKKCoder picture KKKCoder · Nov 8, 2013

LinkedHashMap is still a Map data structure. It maps a unique key to a value. If you assign two different values to a key the second value will simply replace the first value assigned to that key.

Also imagine why do you need a Map of duplicated key? The sole purpose of Map is to provide a one to one relationship between key/value pair. It does not handle one to many relationship.

If you have to map a key with a list of values, use something like:

LinkedHashMap<String, List<..>>

This allows you to have one key maps to a list of values.