Java统计一个字符串中元素出现的次数[ Map实现 ]

public class Test {
   public static void main(String[] args) throws IOException {
        String str = "abcdekka27qoq";
        char[] cs = str.toCharArray();
        HashMap hashMap = new HashMap<>();
        for (char c : cs) {
            Integer value = hashMap.get(c);
            if(value == null){
                hashMap.put(c, 1);
            }else{
                hashMap.put(c, value+1);
            }
        }
        //遍历集合
        String msg = "";
        for (Entry c : hashMap.entrySet()) {
            System.out.print(c.getKey()+"("+c.getValue()+")"+" ");
            msg += c.getKey()+"("+c.getValue()+")"+" ";
        }

  }

}

你可能感兴趣的:(Java统计一个字符串中元素出现的次数[ Map实现 ])