java—如何获取hashmap中存储的名称-值对中的名称字段
我正在尝试解析包含名称-值对的hashmap 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
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
也会比HashMap
也会比