/*使用TreeMap集合实现字符出现次数*/
import java.util.*;
class TreeMaptest
{
public static void main(String[] args)
{
String s = "awaz";
System.out.println(Count(s));
}
public static String Count(String s)
{
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
char []str = s.toCharArray();
int count;
Integer value; //不用int,因为取出元素时当没有对应字符次数时为null
for(int i=0;i<str.length;i++)
{
count = 0; //初始清零
value = tm.get(str[i]);
if (value!=null) //即当TreeMap集合中有该字符时,取出该次数
count = value;
count++;
tm.put(str[i],count);
}
Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();//创建一个set集合,方便取出TreeMap中的内容
Iterator<Map.Entry<Character,Integer>>it = entrySet.iterator();
StringBuilder sb = new StringBuilder(); //用于存放取出后字符元素
Character chs;
while(it.hasNext())
{
Map.Entry<Character,Integer> me = it.next();
chs = me.getKey();
value = me.getValue();
sb.append(chs+"("+value+")");
}
return sb.toString();
}
}
使用TreeMap集合实现统计字符出现次数
最新推荐文章于 2023-03-22 14:58:12 发布