Mainly use HashMap, PriorityQueue (need to specify the sorting rules, sort according to the order from largest to smallest);
import java.util.*;
public class Main {
public static void main(String[] args) {
String str = "helloffjjkfkjdfdsljfoijsgljslgasjgdjfjsdjfldghsojewfsf";
char[] array = str.toCharArray();
//记录字符个数
HashMap<Character,Integer> map = new HashMap<>();
for (int i = 0; i < array.length ; i++) {
map.put(array[i],map.getOrDefault(array[i],0)+1);
}
//根据map的键值对Map.Entry<Chracter,Integer>的value值排序
PriorityQueue<Map.Entry<Character,Integer>> ret = new PriorityQueue<>(10,
(Map.Entry<Character,Integer> a,Map.Entry<Character,Integer> b)->{
return b.getValue()-a.getValue();
});
for(Map.Entry<Character,Integer> ch:map.entrySet()){
ret.offer(ch);
}
//打印输出
while(!ret.isEmpty()){
Map.Entry<Character,Integer> tmp =ret.poll();
System.out.println(tmp.getKey()+" "+ tmp.getValue());
}
}
}
The interviewer said this is a relatively simple method, do you have any other methods?