java【通用】统计字符串中重复【单个】字符的次数频次

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("");
    }

}
 

发布了640 篇原创文章 · 获赞 12 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/xiamaocheng/article/details/105002708