迭代在Java中的HashMap [英] Iterator over HashMap in Java
问题描述
我试图在Java中迭代hashmap,这应该是一件相当容易的事情。但是,下面的代码给了我一些问题:
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();
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()未定义类型迭代器。
First, I needed to cast Iterator on hm.keySet().iterator(), because otherwise it said "Type mismatch: cannot convert from java.util.Iterator to Iterator". But then I get "The method hasNext() is undefined for the type Iterator", and "The method hasNext() is undefined for the type Iterator".
推荐答案
我们能看到您的 import
块吗?因为您似乎导入了错误的 Iterator
类。
Can we see your import
block? because it seems that you have imported the wrong Iterator
class.
您应该使用的是 java.util.Iterator
为了确保这一点,请尝试:
To make sure, try:
java.util.Iterator iter = hm.keySet().iterator();
我个人建议如下:
使用 Generics
并使用接口 Map< K,V>
进行声明并使用实例创建所需的实现 HashMap< K,V>
Map Declaration using Generics
and declaration using the Interface Map<K,V>
and instance creation using the desired implementation 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日
UPDATE 3/5/2015
发现迭代条目集将更好地表现性能:
Found out that iterating over the Entry set will be better performance wise:
for (Map.Entry<Integer, String> entry : hm.entrySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
}
更新 10/3 / 2017
UPDATE 10/3/2017
对于Java8和流,您的解决方案将是
For Java8 and streams, your solution will be
hm.entrySet().stream().forEach(item ->
System.out.println(item.getKey() + ": " + item.getValue())
);
这篇关于迭代在Java中的HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!