• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need logic: Workaround to have duplicate keys in Hashmap  RSS feed

 
Romeo Ranjan
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Ranchers,

I understand the fact that HashMap accepts duplicate values but not duplicate keys. I am stuck with a situation where I need to have duplicate keys is there a workaround for this.Here is my code



Output


Expected Output : The output above plus the below key and value
TOM---->SC14L2


Since the entry TOM is a duplicate key it give only the last entered value for it. Any workaround please???
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could manage it by using a List as your values. So one key would point to a list of values. The logic could look like :
1. Make the key (you already have that)
2. Get the list from the map, using the key.
3. If the list is null, make a new list and put it in the map, using the key.
4. Add the value to the list.
 
Romeo Ranjan
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Christophe,

Thanks for your reply. Can you please elaborate more on the logic, if possible with one line code snippet from my code. Somehow, I am unable to grasp the logic.

Thanks
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd prefer that you figure it out by yourself. Your map would look like Map<String, List<String>>.
Now, you are doing "map.put(val,name);". Instead of that you could:
(pseudocode)
1. list = map.get(val)
2. if list is null -> list = new ArrayList. map.put(val, list)
3. add name into list
 
Campbell Ritchie
Marshal
Posts: 56223
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please search; this sort of question comes up maybe once every other month.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!