在Java中迭代HashMap

问题描述 投票:16回答:7

我试图在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()。iterator()上强制转换Iterator,否则它会说“类型不匹配:无法从java.util.Iterator转换为Iterator”。但后来我得到“方法hasNext()未定义类型Iterator”,并且“方法hasNext()未定义类型Iterator”。

java map iterator
7个回答
43
投票

我们能看到你的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));
}

2015年3月5日更新

发现迭代条目集将更好地表现性能:

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

}

更新10/3/2017

对于Java8和流,您的解决方案将是

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

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

3
投票

使用Java 8:

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

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

        }

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

这比迭代密钥更有效,因为你避免了对get(key)的n次调用。


0
投票

Iterator通过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());

}
© www.soinside.com 2019 - 2024. All rights reserved.