package com.ithemai.map;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
//求一个字符串中每个字符出现的次数 并按字符顺序排序
String source = "sdfasfasdfadf";
String result = countChar(source);
System.out.println(result);
}
public static String countChar(String souce){
String res = "";
//转为字符数组
char[] chars = souce.toCharArray();
//使用treemap记录字符和其出现次数
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
for (int i = 0; i < chars.length; i++) {
if( (chars[i] >= 'a' || chars[i] <= 'z') && (chars[i] >= 'A' || chars[i] <='Z')){
if(tm.containsKey(chars[i])){
Integer count = tm.get(chars[i]);
count++;
tm.put(chars[i], count);
}else{
tm.put(chars[i], 0);
}
}
}
//格式化输出
Set<Entry<Character,Integer>> entrySet = tm.entrySet();
Iterator<Entry<Character, Integer>> entryIte = entrySet.iterator();
while(entryIte.hasNext()){
Entry<Character,Integer> entry = entryIte.next();
res+=entry.getKey()+"("+entry.getValue()+")";
}
return res;
}
}
|