mport java.util.Iterator;标签:java,Iterator,chs,entrySet,value,util,tm From: https://blog.51cto.com/u_10028442/5824711
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/*
* 练习:
* "asdddfgghdsadadf"获取该字符串中的字母出现的次数
* 思路:
* 1.先将字符串转成字符数组
*
* 2.定义一个map集合,因为打印结果的字母有顺序,用treeMap
*
* 3.遍历字符数组,将每一个字母作为键去查map
* 如果返回null,则将字母和1放到map中
* 如果返回不是null,则取出次数自增,重新放入
* 4.按指定形式返回
*/
public class Test {
public static void main(String[] args) {
System.out.println(charCount("asdddfgghdsadadf"));
}
public static String charCount(String str){
char[] chs=str.toCharArray();
TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();
for(int i=0;i<chs.length;i++){
if(!(chs[i]>='a'&&chs[i]<='z'||chs[i]>='A'&&chs[i]<='Z')){
continue;//返回继续循环
}
Integer value=tm.get(chs[i]);
if(value==null){
tm.put(chs[i], 1);
}else{
value=value+1;
tm.put(chs[i], value);
}
}
System.out.println(tm);
StringBuilder sb=new StringBuilder();
Set<Map.Entry<Character,Integer>> entrySet=tm.entrySet();
Iterator<Map.Entry<Character,Integer>> it=entrySet.iterator();
while(it.hasNext()){
Map.Entry<Character,Integer> me=it.next();
Character ch=me.getKey();
Integer value=me.getValue();
sb.append(" "+ch+"("+value+")");
}
return sb.toString();
}
}