import java.util.Map;
import java.util.TreeMap;
public class SetDemo7 {
public static void main(String[] args) {
String str = "aasdfasdgdifjgiosgsdofgbsmvbisdrthweuotpowsdnfgbvi";
//Map<Character, Integer> map = new HashMap<Character, Integer>();
//要想有顺序的话,用下面这个TreeMap, key存储字符名,value存储出现次数
Map<Character, Integer> map = new TreeMap<Character, Integer>();
char[] charArray = str.toCharArray();//将String字符串转换成字符数组
//遍历字符数组,循环的到每一个字符
for (char ch : charArray) {
//判断当前字符是否在Map中的key存在
if (map.containsKey(ch)) {
//当前Map中的key包含该字符,此时取出该key对应的value的值加1,然后在放进去
Integer old = map.get(ch);
map.put(ch, old + 1);
} else {
//当前Map的key不包含该字符,把该字符存储到Map中,设置value的初始值为1
map.put(ch, 1);
}
}
System.out.println(map);
}
}
打印结果:
{a=3, b=3, d=6, e=1, f=4, g=5, h=1, i=4, j=1, m=1, n=1, o=4, p=1, r=1, s=7, t=2, u=1, v=2, w=2}