统计字符串每个字符出现的次数

2 阅读1分钟

1.思路 遍历字符串,利用Map存储key不重复特点,来统计各个字符存在的次数 2.代码实现

public static void main(String[] args) {
    String str = "fabcdefaddffemttqq";
    countCharMethod1(str);
}

public static void countCharMethod1(String str){
    Map<Character,Integer> map = new HashMap<>();
    for (char c : str.toCharArray()) {
        map.put(c, map.getOrDefault(c,1));
    }
    System.out.println(map);
}