Map的使用
public class CharacterCount{
public static void main(String[] args) {
//定义字符串
String str = "sfdsfewew32sadsad324e3";
//将其转化为数组
char[] chars = str.toCharArray();
//定义map集合
Map<Character,Integer> map =new HashMap<>();
//遍历数组
for (char key : chars) {
//定义value
Integer value = map.get(key);
//判断如果包含key,则数量加一,否则数量为一
if(map.containsKey(key)){
map.put(key,value+1);
}else{
map.put(key,1);
}
}
System.out.println(map);
}
}
本文介绍了一种使用Java的HashMap来统计字符串中每个字符出现频率的方法。通过将字符串转换为字符数组,并遍历数组将字符作为键,出现次数作为值存入Map中,实现了对字符频率的有效统计。
582

被折叠的 条评论
为什么被折叠?



