packagecn.itcast.p1.map.test;importjava.util.Iterator;importjava.util.Map;importjava.util.TreeMap;public classTestMap {/*** 练习:
* "fdgavcbsacdfs+++AA&&BBB" 获取该字符串中,每一个字母出现的次数。
* 要求打印结果是:a(2)b(1)...;
* 思路:
* 对于结果的分析发现,字母和次数之间存在着映射的关系。而且这种关系很多。
* 很多就需要存储,能存储映射关系的容器有数组和Map集合。
* 关系一方式有序编号吗?没有!
* 那就是使用Map集合。 又发现可以保证唯一性的一方具备着顺序如 a b c ...
* 所以可以使用TreeMap集合。
*
* 1.因为操作的是字符串中的字母,所以先把字符串变成字符数组
* 2.遍历字符数组,如果该字母不存在,就将该字母的键对应的值为1存储到map中
* 如果,该字母存在,就将该字母的键对应的值+1存储到map中,键相同就会覆盖,
* 这样就记录了每个字母在字符串中出现的次数
* 3.遍历结束map记录所有字母出现的次数*/
public static voidmain(String[] args) {
String str= "asbbbadccfdssf+df-dfucccier%AA+HfffHDAS";
String s=getTreeCount(str);
System.out.println(s);
}public staticString getTreeCount(String str) {//把字符串变成字符数组
char[] ch =str.toCharArray();//定义一个TreeMap用来存储字母和次数的映射关系
Mapmap = new TreeMap();for (int i = 0; i < ch.length; i++) {if(!(ch[i] >= 'a' && ch[i] <= 'z' || ch[i] >= 'A' && ch[i]<='Z')){continue;
}//把字符数组中的字母作为键查map表
Integer value =map.get(ch[i]);int count = 1;if(value != null){
count= value + 1;
}
map.put(ch[i], count);/*if(value == null){
map.put(ch[i], 1);
}else{
map.put(ch[i], value+1);
}*/}returnmapToString(map);
}private static String mapToString(Mapmap) {
StringBuilder sb= newStringBuilder();/*Iterator>it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry mapEntry = it.next();
Character key = mapEntry.getKey();
Integer value = mapEntry.getValue();
sb.append(key+"("+value+")");
}*/Iteratorit =map.keySet().iterator();while(it.hasNext()) {
Character key=it.next();
System.out.println(key);
Integer value=map.get(key);
sb.append(key+"("+value+")");
}returnsb.toString();
}
}