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