Search code examples
javaarraysloopshashmapnumbers

java, given a HashMap, how to organize HM numbers into a new array according to frequency(in hm)?


given a HM that has key-number, value=amount of times repeated.

We sort by highest frequency to lowest frequency. If two elements have same frequency, we sort by increasing value.

now I want to take this HM and sort it according to number frequency(how many times the same number is repeated) and place it inside a new array. here is the function I built(but doesn't work) how can I fix it and even make it more efficient?

public static void findMostFrequent(int[] ar,HashMap<Integer, Integer> t) {
    int frequency=ar[0],k=0;
    for(int i: t.keySet()) {
        for(int j: t.keySet()) { //string(word):all the values together
              if(t.get(j)> frequency) {
                frequency=t.get(j);
                for(int l=k;l<t.get(j);l++ ) {
                    ar[k]=frequency;
                    k++;
                }
                t.remove(frequency);
              }
              }
    }
}

example: given HM(hashmap) -{2=1, 3=3, 5=2, 7=2, 9=1} I want the new array (called ar) to be: (3,3,3,5,5,7,7,2,9) basically the most frequent numbers first to the least frequent words, so if 3 was repeated 3 times and is the most repetitive number then in the new array (3,3,3) and etc... help would be appreciated


Solution

    1. use TreeMap<Integer, Integer>
    2. make frequency as Key, so TreeMap keeps sorted order.
    3. Iterate over Keyset and collect values.

    if you don't have an option to use TreeMap. you can convert it to TreeMap inside your method.

    here is an example:

    public static void findMostFrequent(int[] ar, HashMap<Integer, Integer> t) {
            TreeMap<Integer, Set<Integer>> sortedByVal = new TreeMap<>(Comparator.reverseOrder());
    
            int size=0;
            for (int key : t.keySet()) {
                    int val = t.get(key);
                    sortedByVal.putIfAbsent(val, new HashSet<>());
    
                    Set<Integer> keys = sortedByVal.get(val);
                    keys.add(key);
                    sortedByVal.put(val, keys);
                    size+=val;
                }
    
            ar = new int[size];
            int i = 0;
            for (Integer key : sortedByVal.keySet()) {
                for (int val : sortedByVal.get(key)) {
                   for (int j = 0; j < key; j++) {
                      ar[i++] = val;
                   }
                }
            }
        }