Retrieving hashmap values in java

醉酒当歌 提交于 2019-12-11 06:23:41

问题


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


回答1:


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



回答2:


The problem is you're calling i.next() to get the key, then you call it again to get the value (the value of the next entry).

Another problem is you use toString on the one of the Entry's, which is not the same as getKey or getValue.

You need to do something like:

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



回答3:


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

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



回答4:


You're calling i.next() more than once in the loop. I think this is causing the trouble.

You can try this:

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



回答5:


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>
}


来源:https://stackoverflow.com/questions/15022149/retrieving-hashmap-values-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!