简体   繁体   中英

java- how to obtain name field in name-value pairs stored in a hashmap

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?

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM