Forums Register Login

Need logic: Workaround to have duplicate keys in Hashmap

+Pie Number of slices to send: Send
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???
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
1
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
Please search; this sort of question comes up maybe once every other month.
Crusading Chameleon likes the size of this ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 2763 times.
Similar Threads
Example on Map.Entry methods
How to refresh a StringBuffer object for creating a HashMap object
HELP - Stuck on a TreeMap key problem
Hashtables - Same key many values?
Generics and Colletions
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 19:53:44.