Reputation: 127
Am trying to gives more than one value to a key in a map. I wanted something of this kind to work.. mapp.put("key1","value1") mapp.put("key1","value2"). The first value "value1" is getting over-ridden with "value2". How to retain both the values? Should I go for any other thing than maps for this to happen?
Upvotes: 1
Views: 202
Reputation: 42060
You can use un map with list. Something like that:
Map<String, List<String>> map = new HashMap<String, List<String>>();
For put a key1
with the first value:
if (!map.containsKey("key1")) {
map.put("key1", new LinkedList<String>());
}
map.get("key1").add("value1");
For add the second value to key1
map.get("key1").add("value2");
You can have all this in one method
public void add(String key, String value) {
if (!map.containsKey(key)) {
map.put(key, new LinkedList<String>());
}
map.put(key, value);
}
If you want the values for the key1
, you obtain a List
List<String> values = map.get("key1");
Upvotes: 1
Reputation: 47
HashMap<K, HashSet<V>> map = new HashMap<K, HashSet<V>>();
if(!map.containsKey(k)) {
map.put(k, new HashSet<V>());
}
map.get(k).add(v);
if you have duplicate values, use list/vector instead of hashset.
Upvotes: 1
Reputation: 2262
From the Javadoc of Map,
A map cannot contain duplicate keys; each key can map to at most one value.
So, if you want to put multiple values for single key, you need to add the values to the list and put key1 and list to the map.
Upvotes: 1
Reputation: 129569
Put both valyes into another collection (Vector, Set, Stack, whatever fits your usage; or anything else), and store hat collection as a value in a map.
As a random example using Vector:
Vector<Object> myVector = new Vector<Object>();
myVector.add("value1");
myVector.add("value2");
mapp.put("key1", myVector);
Upvotes: 2