Iterator over HashMap in Java

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

    Can we see your import block? because it seems that you have imported the wrong Iterator class.

    The one you should use is java.util.Iterator

    To make sure, try:

    java.util.Iterator iter = hm.keySet().iterator();
    

    I personally suggest the following:

    Map Declaration using Generics and declaration using the Interface Map and instance creation using the desired implementation HashMap

    Map hm = new HashMap<>();
    

    and for the loop:

    for (Integer key : hm.keySet()) {
        System.out.println("Key = " + key + " - " + hm.get(key));
    }
    

    UPDATE 3/5/2015

    Found out that iterating over the Entry set will be better performance wise:

    for (Map.Entry entry : hm.entrySet()) {
        Integer key = entry.getKey();
        String value = entry.getValue();
    
    }
    

    UPDATE 10/3/2017

    For Java8 and streams, your solution will be (Thanks @Shihe Zhang)

     hm.forEach((key, value) -> System.out.println(key + ": " + value))
    

提交回复
热议问题