Map collection exercises
Given a string, please output which characters the string consists of, and how many times does each character appear?
public static void main(String[] args) {
String str = "321jsdadasgryhrghtyugrgawf";
char[] ch = str.toCharArray();
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < ch.length; i++) {
if(map.containsKey(ch[i])) {
int count = map.get(ch[i]);
map.put(ch[i],count+1);
}else {
map.put(ch[i],1);
}
}
System.out.println(map);
}
输出结果:
{a=3, d=2, f=1, g=4, h=2, j=1, 1=1, 2=1, r=3, 3=1, s=2, t=1, u=1, w=1, y=2}