本文共 1143 字,大约阅读时间需要 3 分钟。
思路:遍历字符串,存入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统计频次"); HashMaphm = new HashMap(); for(int i=0;i > al = new ArrayList<>(hm.entrySet()); Collections.sort(al, new Comparator >() { @Override public int compare(Map.Entry o1, Map.Entry 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个字母或者大小写字母的可以优化
转载地址:http://aexlf.baihongyu.com/