Search code examples
javaarraysfunctionhashmap

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


with a given array which is full of numbers and already made emptied HM, how can I enter all the values from the array to the HM (hashmap) and numbers which are repeated add to the value(starts on 1 if the number is not already in the HM ) of the same key(which is the number). I already wrote a function to do this but it doesn't seem to work. here's my code:

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

help would be appreciated example- array is: [2, 3, 5, 3, 7, 9, 5, 3, 7] HM should be something like this, value is amount of times the same number is repeated): [3(key),3(value)][2,1][5,2][7,2][9,1]


Solution

  • You are trying to print the map in the for a loop. If you want to print only once just print outside the loop.

    Moreover, you can also use getOrDefault

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