public class Test
{
public static void main(String[] args)
{
//key是字符,value是出现的次数
Map<Character, Integer> map = new TreeMap<Character, Integer>();
String str = new String("asldhakhshhaskhdhhshdbf");
char[] chrs = str.toCharArray();
for (int i = 0; i < chrs.length; i++)
{
if (map.get(chrs[i]) == null)
{
map.put(chrs[i], new Integer(1));
}
else
{
int value = ((Integer) map.get(chrs[i])).intValue();
map.put(chrs[i], new Integer(value + 1));
}
}
Set<Map.Entry<Character, Integer>> set = map.entrySet();
for (Iterator<Map.Entry<Character, Integer>> iter = set.iterator(); iter.hasNext();)
{
Map.Entry<Character, Integer> entry = iter.next();
Character key = entry.getKey();
Integer value = entry.getValue();
System.out.print(key + "=" + value + " ");
}
System.out.println();
System.out.println("----------------");
//将Entry对象放入到list当中,以便进行排序,因为Collections.sort接收参数是List类型
List<Map.Entry<Character, Integer>> list = new ArrayList<Map.Entry<Character, Integer>>(set);
//利用Collections自带的排序方法,第二个参数是个内部类,重写方法是自己的比较规则。
Collections.sort(list, new Comparator<Entry<Character, Integer>>()
{
public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2)
{
Map.Entry<Character, Integer> m1 = (Map.Entry<Character, Integer>) o1;
Map.Entry<Character, Integer> m2 = (Map.Entry<Character, Integer>) o2;