1.实现代码
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* 需求:假设给定一个字符串"aasdfsdsdfb",统计各个字符出现的次数,并按次数升序排序
*/
public class SortUtil {
public static void count() throws Exception {
// 定义存储的map集合,使用的是默认排序
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
String line = "aasdfsdsdfb";
int count = 1;
for (int i = 0; i < line.length(); i++) {
Character key = line.charAt(i);
if (!tm.containsKey(key)) {
tm.put(key, count);
} else {
tm.put(key, tm.get(key) + 1);
}
}
printMap(tm);
}
// 打印map集合
public static void printMap(TreeMap<Character, Integer> map) {
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
for (Map.Entry<Character, Integer> it : entrySet) {
Character key = it.getKey();
int count = it.getValue();
System.out.print(key + "(" + count + ")\t");
}
}
public static void main(String[] args) throws Exception {
count();
}
}