Iterator over HashMap in Java

后端 未结 9 1632
醉酒成梦
醉酒成梦 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());
    
    }
    
    0 讨论(0)
  • 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<Integer,String> entry = (Entry<Integer,String>) iter.next();  
             System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
         }  
    
         System.out.println();
    
    
        //Iterating using for-each construct on Entry Set
        Set<Entry<Integer, String>> entrySet = hm.entrySet();
        for (Entry<Integer, String> 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

    0 讨论(0)
  • 2021-02-07 06:28

    With Java 8:

    hm.forEach((k, v) -> {
        System.out.println("Key = " + k + " - " + v);
    });
    
    0 讨论(0)
  • 2021-02-07 06:34
    Map<String, Car> carMap = new HashMap<String, Car>(16, (float) 0.75);
    

    // there is no iterator for Maps, but there are methods to do this.

            Set<String> keys = carMap.keySet(); // returns a set containing all the keys
            for(String c : keys)
            {
    
                System.out.println(c);
            }
    
            Collection<Car> values = carMap.values(); // returns a Collection with all the objects
            for(Car c : values)
            {
                System.out.println(c.getDiscription());
            }
            /*keySet and the values methods serve as “views” into the Map.
              The elements in the set and collection are merely references to the entries in the map, 
              so any changes made to the elements in the set or collection are reflected in the map, and vice versa.*/
    
            //////////////////////////////////////////////////////////
            /*The entrySet method returns a Set of Map.Entry objects. 
              Entry is an inner interface in the Map interface.
              Two of the methods specified by Map.Entry are getKey and getValue.
              The getKey method returns the key and getValue returns the value.*/
    
            Set<Map.Entry<String, Car>> cars = carMap.entrySet(); 
            for(Map.Entry<String, Car> e : cars)
            {
                System.out.println("Keys = " + e.getKey());
                System.out.println("Values = " + e.getValue().getDiscription() + "\n");
    
            }
    
    0 讨论(0)
  • 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<Integer, String> hm = new HashMap<Integer, String>();
    
    hm.put(0, "zero");
    hm.put(1, "one");
    
    for (Map.Entry<Integer, String> 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).

    0 讨论(0)
  • 2021-02-07 06:37
    1. Using EntrySet() and for each loop

         for(Map.Entry<String, String> 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<String> 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

    0 讨论(0)
提交回复
热议问题