统计一个字符串中每个字符出现的次数,并按出现的次数降序输出统计结果

/*
*
*
如统计 abdc2223333ddd
输出如下统计结果
字符3出现了4次
字符d出现了4次
字符2出现了3次
字符b出现了1次
字符c出现了1次
字符a出现了1次
*/


public class CharacterCountTest {
    public static void test(){
    String s="abdc2223333ddd";
    Map<Character, Integer> map=new HashMap<Character, Integer>();
    char[] arr=s.toCharArray();
    for(char c:arr){
        if(map.containsKey(c)){
            int i=map.get(c);
            i++;
            map.put(c, i);
        }else{
            map.put(c, 1);
        }
    }
    List<Map.Entry<Character, Integer>> list=new ArrayList<Map.Entry<Character,Integer>>();
    for(Map.Entry<Character, Integer> me:map.entrySet()){
        list.add(me);
    }
    Collections.sort(list,new MyComparator());
    for(Map.Entry<Character, Integer> me:list){
        System.out.println(me.getKey()+"="+me.getValue());
    }
}
    public static void main(String[] args) {
        test();
    }
}

猜你喜欢

转载自blog.csdn.net/classics_moon/article/details/85100341