Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java—如何获取hashmap中存储的名称-值对中的名称字段_Java_Hashmap - Fatal编程技术网

java—如何获取hashmap中存储的名称-值对中的名称字段

java—如何获取hashmap中存储的名称-值对中的名称字段,java,hashmap,Java,Hashmap,我正在尝试解析包含名称-值对的hashmap hashmap中存储的实体是具有对应于每个单词的数值的单词 这是我正在使用的代码: hMap = (HashMap) untypedResult; /* get Collection of values contained in HashMap using Collection values() method of HashMap class */ c = hMap.values(); //obtain an Iterator f

我正在尝试解析包含名称-值对的hashmap

hashmap中存储的实体是具有对应于每个单词的数值的单词

这是我正在使用的代码:

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());
}
我能够使用上述代码获得与每个单词相关的数值。如何获得每个单词的值呢?

这就是问题所在:

c = hMap.values();
如果还需要这些键,则不应调用
values()
。改为调用
entrySet()

for (Map.Entry<String, Integer> entry : hMap.entrySet()) {
    resp.getWriter().println("Key " + entry.getKey()
                             + "; value " + entry.getValue());
}
这就是问题所在:

c = hMap.values();
如果还需要这些键,则不应调用
values()
。改为调用
entrySet()

for (Map.Entry<String, Integer> entry : hMap.entrySet()) {
    resp.getWriter().println("Key " + entry.getKey()
                             + "; value " + entry.getValue());
}
使用#键集或#entriesSet

使用#键集或#entriesSet


我尝试使用您的代码,但第一行本身(用于(Map.Entry………)我收到了这个错误-类型不匹配:无法从元素类型对象转换为Map.Entry。请告知导致此错误的原因。谢谢。@Arvind:可能是因为使用了原始类型。编辑第二个表单…但如果可能,正确使用泛型类型会更好。甚至
HashMap
也会比更好de>HashMap。我尝试使用您的代码,但第一行本身(用于(Map.Entry………)我收到了这个错误-类型不匹配:无法从元素类型对象转换为Map.Entry。请告知导致此错误的原因。谢谢。@Arvind:可能是因为使用了原始类型。编辑第二个表单…但如果可能,正确使用泛型类型会更好。甚至
HashMap
也会比更好de>HashMap。