使用迭代器循环遍历 Hashmap

我正在尝试计算 java 8 中哈希图的所有值的 mod 总和。但它没有按预期提供。下面是我写的代码。


private static int FindPairs(int n,int[] ar) {

    Map<Integer, Integer> countermap=new HashMap<>();

    Iterator<Integer> itr=countermap.keySet().iterator();

    int result =0;

    for(int i=0;i<ar.length;i++) {

        if(countermap.containsKey(ar[i])) {

            countermap.put(ar[i], countermap.get(ar[i])+1);

        }

        else {

            countermap.put(ar[i], 1);

        }

    }

    int mod=0;


    while(itr.hasNext()) {

        System.out.println(itr.next());

        mod=itr.next()%2;

        result=result + mod;

    }

    System.out.println(Arrays.asList(countermap));

    return result;

}

输入:


ar= {1,2,3,4,5,6,1,3,4,5}


n=7


输出:


[{1=2, 2=1, 3=2, 4=2, 5=2, 6=1}]


0


动漫人物
浏览 115回答 1
1回答

临摹微笑

我在您发布的代码中发现了两个问题您的迭代器必须在填充后创建。HashMap否则永远是空的Iterator<Integer> itr = countermap.keySet().iterator(); <---- HEREwhile (itr.hasNext()) {&nbsp; &nbsp; System.out.println(itr.next());&nbsp; &nbsp; mod = itr.next()% 2;&nbsp; &nbsp; result = result + mod;}此外,连续调用itr.next()两次只会一直跳过一次。您应该调用一次,将其存储在变量中,然后根据需要使用两次Iterator<Integer> itr = countermap.keySet().iterator();while (itr.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;_&nbsp; &nbsp; Integer next = itr.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; System.out.println(next);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}<---- HERE&nbsp; &nbsp; mod = next % 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;_|&nbsp; &nbsp; result = result + mod;}通过这些更改,输出变为以下123456[{1=2, 2=1, 3=2, 4=2, 5=2, 6=1}]3
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java