Hiren Patel
Hiren Patel

Reputation: 52800

Issue with Hashmap. Can not return All values when it has same key. How to get all values?

private HashMap<String, String> mHashMap = new HashMap<String, String>();

mHashMap.put("a", "ajay");
mHashMap.put("h", "hiren");
mHashMap.put("d", "darshan");
mHashMap.put("a", "anand");
mHashMap.put("h", "harsah");

for (String key: mHashMap.keySet()) {

            Log.e(key,"" + mHashMap.get(key));
        }

My Result:

d - darsha
h - harshad
a - anand

I want all values from HashMap? If you have any idea related to it, then help me.

Upvotes: 0

Views: 83

Answers (1)

Blackbelt
Blackbelt

Reputation: 157437

HashMap will override the value if a key for that value exists already. If you need to have more values for a key, you should use a Collection as value fro your HashMap:

private HashMap<String, Vector<String>> mHashMap = new HashMap<String, Vector<String>>();

Vector<String> tmp = new Vector<String>();
tmp.add("ajay"); 
tmp.add("anand");
mHashMap.put("a", tmp);

tmp = new Vector<String>();
tmp.add("hiren");
mHashMap.put("h", tmp);

and so on..

Upvotes: 1

Related Questions