Iterator over HashMap in Java

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

    The cleanest way is to not (directly) use an iterator at all:

    • type your map with generics
    • use a foreach loop to iterate over the entries:

    Like this:

    Map hm = new HashMap();
    
    hm.put(0, "zero");
    hm.put(1, "one");
    
    for (Map.Entry entry : hm.entrySet()) {
        // do something with the entry
        System.out.println(entry.getKey() + " - " + entry.getValue());
        // the getters are typed:
        Integer key = entry.getKey();
        String value = entry.getValue();
    }
    

    This is way more efficient than iterating over keys, because you avoid n calls to get(key).

提交回复
热议问题