Link to home
Start Free TrialLog in
Avatar of shragi
shragiFlag for India

asked on

hashmap count

I created hashmap as below

HashMap<String, String> h = new HashMap<String, String>();                          
h.put("xx", "156");
h.put("xx", "157");    
h.put("xx", "166");
h.put("yy", "176");    
h.put("yy", "179");

now if I want to know how many entries are there in the above hashmap for key "xx" what should I do...
so for above example the count for key "xx" is 3 and count for 'yy' is 2
Avatar of chaau
chaau
Flag of Australia image

There will be one value associated with each of the keys. The HashMap, HashTable, Map, etc. all work as a key=value.  When you first call h.put("xx", "156"); the value at "xx" key is "156". On each of the subsequent calls for the same key (h.put("xx", "157");   h.put("xx", "166");   ) the value for the "xx" key gets overwritten. So, after all your five calls the map will contain two elements. The element with the key "xx" will have a value of "166", and the element with key "yy" will have a value of "179". If you need to store multiple keys in a map you need to use a different collection
Avatar of phoffric
phoffric

It's been awhile since I've worked with Java, so I looked up HashMap put Here is the excerpt:
public V put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Returns:
the previous value associated with key, or null if there was no mapping for key.
Based on this, I would expect that "166" is associated with "xx" and "179" is associated with "yy". Since the keys are distinct, there is only one value associated with one key.
Is it your intention to have multiple values associated with a single key? If so, take a look at the HashMap – Single Key and Multiple Values Example.
Their first example uses a List for the HashMap value.
SOLUTION
Avatar of Jeffrey Dake
Jeffrey Dake
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shragi

ASKER

awesome thanks for all the suggestions I missed the basic point of hashmap.... but I am good now...

I am using the below map and it solves my issue...
Map<String, List<String>> map   = new HashMap<String, List<String>>();

thanks to all again
Shragi -

Just pro-forma (as you shouldn't really be doing it), you could, if you wanted to, do this:

h.put("xx"+"-"+h.size(), "156");

Open in new window

.
.
. etc.,

and then interrogate the Map values with a positional method looking as far as the "-" from the left.

Either way, please don't forget to close your questions - that's important.