I am trying to sort a hashmap that has a structure of by the value from high to Low.
I have created a function below to sort the data.
public static void SortDataHighToLow (Map <String, Integer> UnsortedMap){
List <Integer> list = new ArrayList(UnsortedMap.keySet());
Collections.sort(list,new Comparator <Integer>(){
@Override
public int compare(Integer arg0, Integer arg1) {
return arg0-arg1;
}
});
Map <String, Integer> sortedMap = new LinkedHashMap<>();
for (Integer keys: list){
sortedMap.put(UnsortedMap.toString(), keys);
}
System.out.println(sortedMap);
}
I am recieving the error below:
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
I believe my error is caused by the for() above that I cannot read the Key value.
What adjustment should I make?
Thanks for the help.
keySet- collection of Strings - and define a Comparator of Integers. - AmongalenkeySet()(which is a set ofStrings) to aList<Integer>in the very first line of code in this method... Maybe you wantUnsortedMap.values()instead? - deHaarsortedMap.put(UnsortedMap.toString(), keys);- what is this supposed to do? - Amongalen