Iterator over HashMap in Java

后端 未结 9 1776
醉酒成梦
醉酒成梦 2021-02-07 05:43

I tried to iterate over hashmap in Java, which should be a fairly easy thing to do. However, the following code gives me some problems:

HashMap hm = new HashMap(         


        
9条回答
  •  轮回少年
    2021-02-07 06:27

    You are getting a keySet iterator on the HashMap and expecting to iterate over entries.

    Correct code:

        HashMap hm = new HashMap();
    
        hm.put(0, "zero");
        hm.put(1, "one");
    
        //Here we get the keyset iterator not the Entry iterator
        Iterator iter = (Iterator) hm.keySet().iterator();
    
        while(iter.hasNext()) {
    
            //iterator's next() return an Integer that is the key
            Integer key = (Integer) iter.next();
            //already have the key, now get the value using get() method
            System.out.println(key + " - " + hm.get(key));
    
        }
    

    Iterating over a HashMap using EntrySet:

         HashMap hm = new HashMap();
         hm.put(0, "zero");
         hm.put(1, "one");
         //Here we get the iterator on the entrySet
         Iterator iter = (Iterator) hm.entrySet().iterator();
    
    
         //Traversing using iterator on entry set  
         while (iter.hasNext()) {  
             Entry entry = (Entry) iter.next();  
             System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
         }  
    
         System.out.println();
    
    
        //Iterating using for-each construct on Entry Set
        Set> entrySet = hm.entrySet();
        for (Entry entry : entrySet) {  
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
        }           
    

    Look at the section -Traversing Through a HashMap in the below link. java-collection-internal-hashmap and Traversing through HashMap

提交回复
热议问题