Iterator over HashMap in Java

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

    1. Using EntrySet() and for each loop

         for(Map.Entry entry: hashMap.entrySet()) {
           System.out.println("Key Of map = "+ entry.getKey() + 
                            " , value of map = " + entry.getValue() );
       }
      
    2. Using keyset() and for each loop

               for(String key : hashMap.keySet()) {
                  System.out.println("Key Of map = "+ key + " , 
                            value of map = " + hashMap.get(key) );
                 }
      
    3. Using EntrySet() and java Iterator

            for(String key : hashMap.keySet()) {
              System.out.println("Key Of map = "+ key + " , 
                            value of map = " + hashMap.get(key) );
              }
      
    4. Using keyset() and java Iterator

           Iterator keysIterator = keySet.iterator();
          while (keysIterator.hasNext()) {
              String key = keysIterator.next();
              System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
         }
      

    Reference : How to iterate over Map or HashMap in java

提交回复
热议问题