Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 254
Sunmit Girme Avatar asked Feb 21 '23 21:02

Sunmit Girme


1 Answers

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

like image 139
Chandra Sekhar Avatar answered Mar 05 '23 22:03

Chandra Sekhar