java 在迭代器上显示 Map 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10039742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:21:59  来源:igfitidea点击:

Displaying the contents of a Map over iterator

javamapiterator

提问by Sunmit Girme

I am trying to display the mapi have created using the Iterator. The code I am using is:

我正在尝试显示map我使用迭代器创建的。我正在使用的代码是:

private void displayMap(Map<String, MyGroup> dg) {
Iterator it = dg.entrySet().iterator();   //line 1
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    System.out.println(pair.getKey() + " = " + pair.getValue());
    it.remove();
   }
}

Class MyGroup and it has two fields in it, named idand name. I want to display these two values against the pair.getValue(). The problem here is Line 1 never gets executed nor it throws any exception.

类 MyGroup 并且它有两个字段,namedidname. 我想针对pair.getValue(). 这里的问题是第 1 行永远不会被执行,也不会抛出任何异常。

Please Help.

请帮忙。

PS: I have tried every method on this link.

PS:我已经尝试了此链接上的所有方法。

回答by Chandra Sekhar

Map<String, MyGroup> map = new HashMap<String, MyGroup>();  
for (Map.Entry<String, MyGroup> entry : map.entrySet()) {
     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

using iterator

使用迭代器

Map<String, MyGroup> map = new HashMap<String, MyGroup>();
Iterator<Map.Entry<String, MyGroup>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<String, MyGroup> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

For more iteration information see this link

有关更多迭代信息,请参阅此链接