思路:遍历字符串,存入map统计频次,转存list排序,统计
public class Test {
public static void main(String[] args) {
String str="sdfjklsajfoiwernjkwnerkwndfs";
count(str);
String str2="你我他他他我是好的你说是我";
count(str2);
}
public static void count(String str){
System.out.println("待统计字符:"+str);
System.out.println("HashMap统计频次");
HashMap<Character,Integer> hm = new HashMap();
for(int i=0;i<str.length();i++){
Character one = str.charAt(i);
if(!hm.containsKey(one)){
hm.put(one,1);
}else{
hm.put(one,hm.get(one) +1);
}
}
for(Map.Entry entry: hm.entrySet()){
System.out.println(entry.getKey()+" "+entry.getValue());
}
System.out.println("map存到list,按频次排序");
ArrayList< Map.Entry<Character,Integer> > al = new ArrayList<>(hm.entrySet());
Collections.sort(al, new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
return o2.getValue() - o1.getValue(); //倒序
}
});
for(Map.Entry entry: al){
System.out.println(entry.getKey()+" "+entry.getValue());
}
System.out.println("------------------------------");
int maxCount = al.get(0).getValue();
System.out.println("重复最多次数:"+maxCount);
System.out.print("重复最多的字符是:");
for(Map.Entry entry: al){
if (entry.getValue().equals(maxCount) ){
System.out.print(entry.getKey());
}else {
break; //已排好序,不相等就不是重复最多的
}
}
System.out.println("");
}
}
针对只统计26个字母或者大小写字母的可以优化