0
import java.util.*;  
class TestCollection13{  
    public static void main(String args[]){  
        HashMap<Integer,String> hm=new HashMap<Integer,String>();  

        hm.put(100,"Amit");  
        hm.put(101,"Vijay");  
        hm.put(102,"Rahul");  

        for(Map.Entry m:hm.entrySet()){  
            System.out.println(m.getKey()+" "+m.getValue());  
        }  
    }  
}  

in this above HaspMap program i can not understand the logic behind this for loop . why Map.Entry is needed and what is the function of entrySet() ?? help me regarding this please . thanks in advance

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
prtk
  • 21
  • 3

1 Answers1

1

The for loop iterates over all the entries in the HashMap. The entrySet() will return all key-value pairs in the map.

Map.Entry is just the type of a key-value pair (just as String is a type).

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • `public class MyHash { public static void main(String a[]){ HashMap hm = new HashMap(); hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third","THIRD INSERTED"); System.out.println(hm); Set keys = hm.keySet(); for(String key: keys){ System.out.println("Value of "+key+" is: "+hm.get(key)); } } }` i can do this program by this way also .what is the difference between this two???.here we dont use Map.Entry for a key value pair ... – prtk Jul 27 '15 at 04:57