In Java, Map
s do not allow duplicate keys. So, to associate multiple values you'll need to assign every key a List
instead. Also, notice how I'm using an interface type on the reference side.
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
Now you just have to create your own put()
version that adds to these List
s instead.
public void add(Integer key, String val) {
List<String> list = map.get(key);
if (list == null) {
list = new ArrayList<String>();
map.put(key, list);
}
list.add(val);
}
Here's how you would add and display multiple values
add(1, "one");
add(2, "two");
add(2, "three");
for(Map.Entry<Integer, List<String>> entry: map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
Output :
1 = [one]
2 = [two, three]