2013-03-14 79 views
15

我試着迭代Java中的hashmap,這應該是一件相當容易的事情。但是,下面的代碼給了我一些問題:Java中的HashMap上的迭代器

HashMap hm = new HashMap(); 

hm.put(0, "zero"); 
hm.put(1, "one"); 

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

while(iter.hasNext()) { 

    Map.Entry entry = (Map.Entry) iter.next(); 
    System.out.println(entry.getKey() + " - " + entry.getValue()); 

} 

首先,我需要投迭代器上hm.keySet()迭代器(),否則它說:「類型不匹配:不能從java.util中轉換。迭代器到迭代器「。但後來我得到「方法hasNext()未定義類型Iterator」,並且「方法hasNext()未定義類型Iterator」。

+5

聽起來就像你導入了錯誤的'Iterator'類。你會想要導入'java.util.Iterator'。 – Vulcan 2013-03-15 00:01:06

+2

如果你想要的是entires而不是key,你需要遍歷entrySet()而不是keySet()。 – 2013-03-15 00:09:13

回答

39

我們能看到你的import塊?因爲你似乎已經輸入了錯誤的Iterator類。

你應該使用的一個是java.util.Iterator

要確保,嘗試:

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

我個人建議如下:

使用使用Generics和申報地圖聲明界面Map<K,V>和實例創建使用期望實現HashMap<K,V>

Map<Integer, String> hm = new HashMap<>(); 

和循環:

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

UPDATE 2015年3月5日

發現,遍歷條目集將是明智的更好的性能:

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

} 

UPDATE 2017年10月3日

對於Java8和溪流,你的解決方案將是

hm.entrySet().stream().forEach(item -> 
        System.out.println(item.getKey() + ": " + item.getValue()) 
      ); 
+2

您的更新解決方案也是我的最愛;-) – zypro 2016-09-08 09:57:44

6

你真的應該使用泛型和增強的for循環此:

Map<Integer, String> hm = new HashMap<>(); 
hm.put(0, "zero"); 
hm.put(1, "one"); 

for (Integer key : hm.keySet()) { 
    System.out.println(key); 
    System.out.println(hm.get(key)); 
} 

http://ideone.com/sx3F0K

還是entrySet()版本:

Map<Integer, String> hm = new HashMap<>(); 
hm.put(0, "zero"); 
hm.put(1, "one"); 

for (Map.Entry<Integer, String> e : hm.entrySet()) { 
    System.out.println(e.getKey()); 
    System.out.println(e.getValue()); 
} 
+0

你能否指定兩種方法之間的區別? – 2014-05-24 03:53:34

+0

@ HussainAkhtarWahid'Ghouri'實際上沒有 - 這就是爲什麼我沒有提到任何。由於避免每次迭代中的哈希查找,因此第二個速度可能會快得可以忽略不計。 (或者它可能不是。) – millimoose 2014-05-26 15:32:06

+0

如果他需要修改他的地圖怎麼辦?它會引起併發修改異常。 – Eddnav 2015-08-13 16:14:28

0

最乾淨的方法是不(直接)使用迭代器都:

  • 類型您的帶有仿製藥的地圖
  • 使用foreach循環遍歷條目:

像這樣:

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(); 
} 

這個方式比遍歷鍵更有效,因爲你避免n次的調用來get(key)

+0

將JM更改爲hm。我想......糾正我,如果我錯了:) – Neo 2014-08-11 18:08:34

+0

@neo thx。這一定是一個iPhone自動更正:/ – Bohemian 2014-08-11 22:42:48

0

這裏的幾個問題:

  • 你可能不使用正確的迭代器類。正如其他人所說,使用import java.util.Iterator
  • 如果要使用Map.Entry entry = (Map.Entry) iter.next();那麼您需要使用hm.entrySet().iterator()而不是hm.keySet().iterator()。您可以在鍵上或條目上進行迭代。
0
Map<String, Car> carMap = new HashMap<String, Car>(16, (float) 0.75); 

//沒有用於地圖沒有迭代,但也有方法來做到這一點。

 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"); 

     } 
3

與Java 8:

hm.forEach((k, v) -> { 
    System.out.println("Key = " + k + " - " + v); 
}); 
+0

這是太容易與Java 8真棒 – AndroidLover 2016-04-19 15:28:43

0

迭代器通過keySet會給你鑰匙。如果要迭代條目,則應該使用entrySet

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()); 

}