0

I want to write a piece of code in java that takes in an hashMap that is sorted in descending values. It only rearranges the pairs that have more than one duplicate values and order them in ascending key order. So {7=4, 17=2, 5=2} hashMap would result in {7=4, 5=2, 17=2}. For another example {7=4, 11=3 , 18=3 , 35=3, 2=2, 5=1, 11,1} would equal {7=4, 11=3 , 18=3 , 35=3, 2=2, 5=1, 11,1} since all the duplicates are already sorted in ascending keys. The code down below is wrong and does not give the expected value described. Please change the code below for it to perform what its supposed to. The pair 11=3 is also missing in the output.

Input:{7=4, 11=3 , 18=3 , 35=3, 2=2, 5=1, 11,1}
Output: {2=2, 18=3, 35=3, 5=1, 7=4, 11=1}
Expected Output: {7=4, 11=3 , 18=3 , 35=3, 2=2, 5=1, 11=1}

Code

import java.util.*;

public class HashMapSort {
    public static void main(String[] args) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        hashMap.put(7, 4);
        hashMap.put(11, 3);
        hashMap.put(18, 3);
        hashMap.put(35, 3);
        hashMap.put(2, 2);
        hashMap.put(5, 1);
        hashMap.put(11, 1);
        System.out.println("Before rearranging: " + hashMap);
        HashMap<Integer, Integer> rearrangedHashMap = rearrangeHashMap(hashMap);
        System.out.println("After rearranging: " + rearrangedHashMap);
    }

    public static HashMap<Integer, Integer> rearrangeHashMap(HashMap<Integer, Integer> hashMap) {
        HashMap<Integer, Integer> rearrangedHashMap = new HashMap<>();
        // Group the values by count and by whether they have duplicates
       HashMap<Integer, List<Integer>> groupedValues = new HashMap<>();
        for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
            int key = entry.getKey();
            int value = entry.getValue();
            if (value > 1) {
                groupedValues.computeIfAbsent(value, k -> new ArrayList<>()).add(key);
            } else {
                rearrangedHashMap.put(key, value);
            }
        }
        // Rearrange the groups with multiple values
        for (Map.Entry<Integer, List<Integer>> entry : groupedValues.entrySet()) {
            int value = entry.getKey();
            List<Integer> keys = entry.getValue();
            Collections.sort(keys, Collections.reverseOrder());
            for (int key : keys) {
                rearrangedHashMap.put(key, value);
            }
        }
        return rearrangedHashMap;
    }
}

Bosser445
  • 303
  • 1
  • 9
  • This might be helpful: https://stackoverflow.com/a/26296947/5900660 – Conor Egan May 23 '23 at 20:17
  • Additionally, when you call `put()` it is replacing the original value for that key in the hashmap. A better solution would be to map an integer to a list of integers. HashMap>. – Conor Egan May 23 '23 at 20:22
  • Where is the difference between the input and the expected output, what am I missing? – Reilas May 23 '23 at 20:39
  • Yes, as @ConorEgan mentioned, since the `Map` keys need to be unique, the second assignment of `11` will over-write the current value. If you're looking to store more than one value per key, use a `List` as the value. – Reilas May 23 '23 at 20:43
  • 1
    _ an hashMap that is sorted in descending values._ - that is impossible. HashMaps aren't ordered. If you put in keys 'a', 'b', 'c' - and then immediately iterate, you get an arbitrary order back. You can sort _on keys_ (`TreeMap`). You can't sort on values. – rzwitserloot May 23 '23 at 21:03
  • @rzwitserloot, agreed; at least, not intrinsically, it's not part of the abstraction. You'd have to create some sort of iteration on a `LinkedHashMap`, and re-order the keys. – Reilas May 23 '23 at 21:07

1 Answers1

2

Here is a possible solution to your inquiry.

Firstly, you can use a Map<Integer, List<Integer>>, as a way to hold more than one value per key.

When adding a new value, sort the List using Comparator.reverseOrder.

public class Example {
    Map<Integer, List<Integer>> map = new LinkedHashMap<>();

    void add(int key, int value) {
        if (!map.containsKey(key))
            map.put(key, new ArrayList<>(List.of(value)));
        else {
            map.get(key).add(value);
            map.get(key).sort(Comparator.reverseOrder());
        }
    }
}

Here is an example usage

Example example = new Example();
example.add(7, 4);
example.add(11, 3);
example.add(18, 3);
example.add(35, 3);
example.add(2, 2);
example.add(5, 1);
example.add(11, 1);

System.out.println(example.map);

Output

{7=[4], 11=[3, 1], 18=[3], 35=[3], 2=[2], 5=[1]}
Reilas
  • 3,297
  • 2
  • 4
  • 17