dcsimg
Map with duplicate keys
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Friday, July 14, 2006 08:55 AM

Hi,
Java reference says that a Map, HashMap or Hashtable does not allow to store multiple entries with a same key. I have the requirement to store multiple entries (basically key-value pairs) into some collection with a same key. Is there any collection to handle such a situation?

Thanks in advance,
Ajay

Re: Map with duplicate keys

Posted By:   WarnerJan_Veldhuis  
Posted On:   Friday, July 14, 2006 09:10 AM

One solution is to use a Map, that stores a List as value. When adding a new KV-pair, check if the key exists. If it does NOT exist, create a new List, add the value to the List and add it to the Map. If the key DOES exist, get the List and add the value to the List:

if ( ! map.containsKey( key ) ) {
List list = new ArrayList( );
list.add( value);
map.put( key, list);
}
else {
List list = (List) map.get(key);
list.add( value );
}


Or if you want to have a single list.add():

if ( ! map.containsKey( key ) ) {
List list = new ArrayList( );
map.put( key, list);
}

List list = (List) map.get(key);
list.add( value );
About | Sitemap | Contact