Reputation: 1188
I have gone through questions relate to the same questions, but I am not getting a clear idea of how to implement the map with duplicate entries. I was asked this question in my interview. Please give me some guidelines.
For instance, a company has two employees of same name and same area of development viz.
map.put("Tom Hank","Java");
map.put("Tom Hank","Java");
As we all know, we cannot store duplicate values in HashMap
. So can I implement this and retrieve the values according to key? Or any other better solution?
These are the questions that I have gone through but not able to understand how to do this.
How to include duplicate keys in HashMap? | How can i have a HashMap in Java with duplicate keys
Upvotes: 1
Views: 27213
Reputation: 337
I hope this will help you:
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections.MultiHashMap;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.HashedMap;
public class TryingMultiMap {
public Map<String, String> testMap(MultiMap m) {
Map<String, String> m_copy = new HashMap();
m_copy.putAll(m);
System.out.println(m_copy);
return m_copy;
}
public static void main(String[] args) {
System.out.println("test");
MultiMap m = new MultiHashMap();
m.put("Bhaskar","Java");
m.put("Bhaskar","Java");
m.put("Ravi",".Net");
m.put("Ravi", ".Net");
m.put("Suyash","C++");
System.out.println(m);
/*Map exhibitMap= new HashMap();
h.put("Bhaskar", "Java");
h.put("Bhaskar", "Java");
System.out.println("exhibitMap"+ExhibitMap)*/;
TryingMultiMap obj = new TryingMultiMap();
obj.testMap(m);
}
}
How it brings in your problem into picture, is by having a multimap which can contain duplicates. Finally, multimap is put in the map and you find the MultiMap with duplicates added in the new Map too. Also, find the commented code in the main method, which exhibits the fact that Map cannot hold duplicates.
However, I find the solution provided by Armas is also a very appropriate one. Hope it helps :)
Upvotes: 4
Reputation: 8802
Type multimaps in Google, and you will find what you are looking for.
Another way of doing it would be doing a simulated multimap the following way:
Map<String, List<String>> multimap=new Map<String, List<String>>();
if (multimap.contains("Tom Hanks"){
multimap.get("Tom Hanks").add("value2");
}
else {
List<String> values=new ArrayList<String>();
values.add("value1");
multimap.put("Tom Hanks", values);
}
But finding a multimaps implementation will save you all the trouble.
Upvotes: 2
Reputation: 626
Map does not supports duplicate keys. you can use collection as value against same key.
Because if the map previously contained a mapping for the key, the old value is replaced by the specified value.
Map<Integer, List<String>>
you can use something like this.
Upvotes: 4