Sanjay Kumar wrote
I have HashMap with two identical keys, but different values. If do a
"get(key name)" on the HashMap Object I don't get both values. I know this
how it is supposed to work. The question - is there any data structure in java
which will return values for identical keys ?
The Map interface do not directly support implementations that map a key to
multiple values. However, since values can be any object you like, including
other collections, you can perhaps use another Collection inside your Map,
like in the following example:
public class MyMap {
private Map map = new HashMap();
public void add(Object key, Object value) {
Collection values = get(key);
if (values == null) {
values = new HashSet(); // use whatever collection makes sense
map.put(key,values);
}
values.add(value);
}
public void remove(Object key, Object value) {
Collection values = get(key);
if (values == null) return;
values.remove(value);
if (values.isEmpty()) {
map.remove(key);
}
}
public Collection get(Object key) {
return (Collection) map.get(key);
}
// delegate to other map methods as needed ...
}
So, with
MyMap myMap = new MyMap();
myMap.add(key,value1);
myMap.add(key,value2);
you can iterate now over the elements for key by doing
Iterator i = myMap.get(key).elements();
while (i.hasNext()) {
Object myValue = i.next();
}