java【通用】统计字符串中重复【单个】字符的次数频次并输出重复最多的次数和字符

思路:遍历字符串,存入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个字母或者大小写字母的可以优化

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值