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???
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.
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.
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