下面是实现方法
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;
Integer i1 = m1.getValue();
Integer i2 = m2.getValue();
return i1 - i2;
}
});
for(Iterator<Map.Entry<Character, Integer>> iter = list.iterator(); iter.hasNext();)
{
System.out.print(iter.next() + " ");
}
}
}
运行结果:
a=3 b=1 d=3 f=1 h=8 k=2 l=1 s=4
----------------
b=1 f=1 l=1 k=2 a=3 d=3 s=4 h=8 |