package cn.itcast.heima;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class Demo1 {
/*
* 需求分析:取出一个字符串中字母出现的次数。
* 如:字符串:"abcdekka27qoq" ,输出格式为:a(2)b(1)k(2)...
*
*/
public static void main(String[] args) {
statisticLetterCount("abcdewwkka27qoq");
}
public static void statisticLetterCount(String target)
{
if(target == null)
{
System.out.println("被统计的字符串不能为空");
return;
}
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0; i < target.length(); i++)
{
char data = target.charAt(i);
if(!('a'<=data && data<='z' || 'A'<=data && data<='Z')) //取到数据就进行判断是否为需要统计的字符,这样效率更高
continue;
Integer count = map.get(new Character(data));
if(count == null )
{
map.put(data,new Integer(1)); //虽然可以自动装箱,但是主动的去强转比隐式效率要高
}
else
{
count++;
map.put(new Character(data), count);//这里也是一样
}
}
Set<Map.Entry<Character, Integer>> set = map.entrySet();
TreeSet<String> ts = new TreeSet<String>();
for(Map.Entry<Character,Integer> entry: set)
{
Character key = entry.getKey();
Integer value = entry.getValue();
String data = key +"(" +value+")";
ts.add(data);
}
for(String str:ts)
{
System.out.print(str + " ");
}
}
}
|