Reputation: 6474
I am trying to parse a hashmap that contains name-value pairs...
The entities stored in the hashmap are words with a numerical value corresponding to each word.
This is the code that I am using:
hMap = (HashMap) untypedResult;
/*
get Collection of values contained in HashMap using
Collection values() method of HashMap class
*/
c = hMap.values();
//obtain an Iterator for Collection
Iterator itr = c.iterator();
//iterate through HashMap values iterator
while(itr.hasNext())
{
resp.getWriter().println(" Value= " + itr.next());
//resp.getWriter().println(" To String of iterator= " + itr.toString());
}
I am able to obtain the numerical values associated with each word using the above code. How do I obtain the value of each word as well?
Upvotes: 0
Views: 735
Reputation: 1500495
This is the problem:
c = hMap.values();
If you want the keys as well, you shouldn't call values()
. Call entrySet()
instead:
for (Map.Entry<String, Integer> entry : hMap.entrySet()) {
resp.getWriter().println("Key " + entry.getKey()
+ "; value " + entry.getValue());
}
Or for the raw type (ick):
for (Object rawEntry : hMap.entrySet()) {
Map.Entry entry = (Map.Entry) rawEntry;
resp.getWriter().println("Key " + entry.getKey()
+ "; value " + entry.getValue());
}
Upvotes: 4
Reputation: 31903
Either with #keySet or #entriesSet
http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html
Upvotes: 0