Iterator over HashMap in Java

后端 未结 9 1647
醉酒成梦
醉酒成梦 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:26

    Iterator through keySet will give you keys. You should use entrySet if you want to iterate entries.

    HashMap hm = new HashMap();
    
    hm.put(0, "zero");
    hm.put(1, "one");
    
    Iterator iter = (Iterator) hm.entrySet().iterator();
    
    while(iter.hasNext()) {
    
        Map.Entry entry = (Map.Entry) iter.next();
        System.out.println(entry.getKey() + " - " + entry.getValue());
    
    }
    

提交回复
热议问题