2013-02-22 107 views
1

我写下面的代码来检索hashmap中的值。但它没有工作。在java中检索hashmap值

HashMap<String, String> facilities = new HashMap<String, String>(); 

Iterator i = facilities.entrySet().iterator(); 

while(i.hasNext()) 
{ 
    String key = i.next().toString(); 
    String value = i.next().toString(); 
    System.out.println(key + " " + value); 
} 

我修改了包含SET类的代码,它工作正常。

Set s= facilities.entrySet(); 
Iterator it = facilities.entrySet().iterator(); 
while(it.hasNext()) 
{ 
    System.out.println(it.next()); 
} 

任何人都可以指导我出了什么差错在上面的代码中没有SET类?

P.S - 我没有太多的编程exp和使用Java最近

+2

你跟HashMap中得到什么错误,即会显示什么? – Prateek 2013-02-22 10:38:21

+1

你期望什么,你是什么感受? – Behe 2013-02-22 10:46:34

+0

我没有收到任何错误。但是输出屏幕中没有显示任何内容。所以我GOOGLE了,并使用SET类。然后显示值。所以我的问题是为什么没有显示没有SET类的值? – Neil 2013-02-22 11:00:46

回答

10

要调用next()两次启动。

试试这个:

while(i.hasNext()) 
{ 
    Entry e = i.next(); 
    String key = e.getKey(); 
    String value = e.getValue(); 
    System.out.println(key + " " + value); 
} 

总之你也可以使用下面的代码(这也保持类型的信息)。以某种方式使用Iterator是Java-1.5之前的样式。

for(Entry<String, String> entry : facilities.entrySet()) { 
    String key = entry.getKey(); 
    String value = entry.getValue(); 
    System.out.println(key + " " + value); 
} 
2

的问题是你打电话i.next()拿到钥匙,然后你再调用它来获取值(下一个条目的值)。

另一个问题是您在Entry的其中一个上使用toString,这与getKeygetValue不一样。

你需要做的是这样的:

Iterator<Entry<String, String>> i = facilities.entrySet().iterator(); 
... 
while (...) 
{ 
    Entry<String, String> entry = i.next(); 
    String key = entry.getKey(); 
    String value = entry.getValue(); 
    ... 
} 
0
Iterator i = facilities.keySet().iterator(); 

while(i.hasNext()) 
{ 
    String key = i.next().toString(); 
    String value = facilities.get(key); 
    System.out.println(key + " " + value); 
} 
+0

这不会导致最佳性能。在我看来,这个代码更难以阅读。 – Kai 2013-02-22 10:50:06

0

你打电话i.next()比循环一次。我认为这是造成麻烦。

你可以试试这个:

HashMap<String, String> facilities = new HashMap<String, String>(); 
Iterator<Map.Entry<String, String>> i = facilities.entrySet().iterator(); 
Map.Entry<String, String> entry = null; 
while (i.hasNext()) { 
    entry = i.next(); 
    String key = entry.getKey(); 
    String value = entry.getValue(); 
    System.out.println(key + " " + value); 
} 
0
String key; 
for(final Iterator iterator = facilities.keySet().iterator(); iterator.hasNext();) {<BR> 
    key = iterator.next();<BR> 
    System.out.println(key + " : " + facilities.get(key));<BR> 

for (Entry<String, String> entry : facilities.entrySet()) {<BR> 
System.out.println(entry.getKey() + " : " + entry.getValue();<BR> 
}