java,帮助使用HM(hashmap)&提高效率。使用给定的数组和给定的数字在 HM 中正确放置重复和不重复的数字

java, help using HM(hashmap)& improve efficiency. with given array with given numbers to place repetitive & non repetitive numbers in the HM correctly

对于一个充满数字并且已经清空 HM 的给定数组,我如何将数组中的所有值输入到 HM(散列图)中,并将重复的数字添加到值中(如果从 1 开始,则该号码不在同一键(即号码)的 HM 中)。我已经编写了一个函数来执行此操作,但它似乎不起作用。 这是我的代码:

public static void placeInHM(int[] array,HashMap<Integer, Integer> t ) {
        for(int i: array) {
            if(t.containsKey(i)) {
                t.replace(i,t.get(i)+1);
            }
            else {
                t.put(i, 1);
            }
            System.out.println(t);
    }
}

帮助将不胜感激 示例数组是:[2, 3, 5, 3, 7, 9, 5, 3, 7] HM应该是这样的,值是相同数字重复的次数):[3(key),3(value)][2,1][5,2][7,2][9,1]

您正在尝试在 for 循环中打印地图。 如果只想打印一次,只需在循环外打印即可。

此外,您还可以使用getOrDefault

   for(int i: array) {
     t.put(i, t.getOrDefault(i,0)+1);  
}