統計一個字串中每個字元出現的次數,並按出現的次數降序輸出統計結果
阿新 • • 發佈:2018-12-21
/*
*
*
如統計 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();
}
}