Java [hashmap][iterator]给出一半的值

Java [hashmap][iterator]给出一半的值,java,hashmap,iterator,Java,Hashmap,Iterator,我一直在编写一个简单的HashMap迭代程序,遇到了以下问题: HashMap<String, Integer> hm1 = new HashMap<String, Integer>(); hm2.put("One", 1); hm2.put("Two", 2); hm2.put("Three", 3); hm2.put("Four", 4); hm2.put("Five", 5); hm2.put("Six", 6); Set<String> keySe

我一直在编写一个简单的HashMap迭代程序,遇到了以下问题:

HashMap<String, Integer> hm1 = new HashMap<String, Integer>();
hm2.put("One", 1);
hm2.put("Two", 2);
hm2.put("Three", 3);
hm2.put("Four", 4);
hm2.put("Five", 5);
hm2.put("Six", 6);


Set<String> keySet = hm2.keySet();
Iterator<String> itr = keySet.iterator();

while(itr.hasNext())
{
    String key = itr.next();
    System.out.println("Key: " + key + "Values:" + hm2.get(itr.next()));
}
HashMap hm1=newhashmap();
hm2.put(“一”,1);
hm2.put(“两个”,2);
hm2.put(“三”,3);
hm2.put(“四”,4);
hm2.put(“五”,5);
hm2.put(“六”,6);
设置keySet=hm2.keySet();
迭代器itr=keySet.Iterator();
while(itr.hasNext())
{
String key=itr.next();
System.out.println(“Key:+Key+”值:+hm2.get(itr.next());
}

问题-
hm2.get(itr.next())
在输出中只给出3个值,而如果我使用hm2.get(key),那么它将列出所有6个值。为什么会这样?

这是因为无论何时执行此操作,迭代器都会向前移动一步并返回值。因此,当您在一次迭代中调用两次
itr.next()
时,只会得到3个值,而当您只调用一次时,会得到全部6个值。因此,如果您使用了所有六个值,那么您应该使用
hm2.get(key)

在循环中推进迭代器(通过调用
next()
)两次,从而“跳过”了一半的值。每次选中
hasNext()
时,只应调用
next()
一次。在这种情况下,只需重用本地
变量:

Set<String> keySet = hm2.keySet();
Iterator<String> itr = keySet.iterator();
while(itr.hasNext())
{
    String key = itr.next();
    System.out.println("Key: " + key + "Values:" + hm2.get(key));
}
或者,更优雅的是,通过增强的for循环:

for (Map.Entry<String, Integer> entry : hm2.entrySet()) 
{
    System.out.println("Key: " + entry.getKey() + "Values:" + entry.getValue());
}
for(Map.Entry:hm2.entrySet())
{
System.out.println(“Key:+entry.getKey()+”值:“+entry.getValue());
}

我建议您使用Map.Entry接口来迭代Map

    HashMap<String, Integer> hm2 = new HashMap<String, Integer>();
    hm2.put("One", 1);
    hm2.put("Two", 2);
    hm2.put("Three", 3);
    hm2.put("Four", 4);
    hm2.put("Five", 5);
    hm2.put("Six", 6);


    for(Map.Entry<String, Integer> e: hm2.entrySet()) {
        System.out.println("Key: " + e.getKey() + " Values:" + e.getValue());
    }
HashMap hm2=newhashmap();
hm2.put(“一”,1);
hm2.put(“两个”,2);
hm2.put(“三”,3);
hm2.put(“四”,4);
hm2.put(“五”,5);
hm2.put(“六”,6);
对于(Map.Entry e:hm2.entrySet()){
System.out.println(“Key:+e.getKey()+”值:+e.getValue());
}
或类似于hm2.forEach((key,val)->{System.out.println(“key:+key+”值:+val);});
    HashMap<String, Integer> hm2 = new HashMap<String, Integer>();
    hm2.put("One", 1);
    hm2.put("Two", 2);
    hm2.put("Three", 3);
    hm2.put("Four", 4);
    hm2.put("Five", 5);
    hm2.put("Six", 6);


    for(Map.Entry<String, Integer> e: hm2.entrySet()) {
        System.out.println("Key: " + e.getKey() + " Values:" + e.getValue());
    }