在java中检索hashmap值 [英] Retrieving hashmap values in java
本文介绍了在java中检索hashmap值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HashMap< String,String> facilities = new HashMap< String,String>();
Iterator i = facilities.entrySet()。iterator(); (i.hasNext())
{
String key = i.next()。toString();
while
字符串值= i.next()。toString();
System.out.println(key ++ value);
}
我修改了包含SET类的代码,它工作正常。
Set s = facilities.entrySet();
Iterator it = facilities.entrySet()。iterator(); (it.hasNext())
(
)System.out.println(it.next());
$ b 任何人都可以引导我在没有SET类的代码中出了什么问题??
PS - 我没有太多的编程exp,并且最近开始使用java
解决方案您打电话给 next()
两次。
试试这个:
while(i.hasNext())
{
Entry e = i.next();
String key = e.getKey();
字符串值= e.getValue();
System.out.println(key ++ value);
}
总之,您还可以使用下面的代码(它也保留类型信息)。 使用 Iterator
是某种程度上的Java-1.5风格。
for条目< String,String>条目:facilities.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key ++ value);
}
I wrote below code to retrieve values in hashmap. But it didnt work.
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);
}
I modified the code to include SET class and it worked fine.
Set s= facilities.entrySet();
Iterator it = facilities.entrySet().iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
Can anyone guide me what went wrong in above code without SET class??
P.S - I do not have much programming exp and started using java recently
解决方案 You are calling next()
two times.
Try this instead:
while(i.hasNext())
{
Entry e = i.next();
String key = e.getKey();
String value = e.getValue();
System.out.println(key + " " + value);
}
In short you could also use the following code (which also keeps the type information). Using Iterator
is pre-Java-1.5 style somehow.
for(Entry<String, String> entry : facilities.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " " + value);
}
这篇关于在java中检索hashmap值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文