Displaying the Contents of a Map over Iterator

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

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 id and 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.

Please Help.

PS: I have tried every method on this link.

5

1 Answer

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

4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest