I want my code to sort my hashmap based on a value. The user will input the string and it'll count the number of occurrences. The character and its occurrence will be stored into a hasmap. It should be sorted in ascending order not caring about its keys. In my code, if they all have the same value, it sorts in alphabetical order. I don't want it to sort if they have the same values.
Desired output:
Enter a string: maabccc
m: 1
b: 1
a: 2
c: 3
Program's output:
Enter a string: maabccc
b: 1
m: 1
a: 2
c: 3
public static void main(String args[]){
System.out.print("Enter a string: ");
string = input.nextLine();
char newChar[] = string.toCharArray();
int count[] = countFrequency(string);
Map<Character, Integer> sortedMap = sortByComparator(hm);
for(Entry<Character, Integer> entry : sortedMap.entrySet()){
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
public static Map<Character, Integer> sortByComparator(Map<Character, Integer> unsortMap){
List<Entry<Character, Integer>> list = new LinkedList<>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Entry<Character, Integer>>(){
@Override
public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2){
return o1.getValue().compareTo(o2.getValue());
}
});
Map<Character, Integer> sortedMap = new LinkedHashMap<>();
for(Entry<Character, Integer> entry : list)
sortedMap.put(entry.getKey(), entry.getValue());
return sortedMap;
}