使用 HashMap 计算字符

Counting character with HashMap

我正在尝试计算字符串中的所有字符(“Hello”),但代码无法正常工作。我只是不知道如何让代码做我想做的事。

这就是我尝试的原因:

    char[] array = hello.toCharArray();
    HashMap<Character, Integer> hashMap = new HashMap<>();
    // hashMap.put('a', 1);
    int occurence = 1;
    char currentChar = ' ';

    for (int i = 0; i < array.length; i++) {
        hashMap.put(hello.charAt(i), occurence);
        currentChar = hello.charAt(i);

        for (int j = 0; j < hashMap.size(); j++) {
            if (hashMap.containsKey(currentChar)) {
                hashMap.put(currentChar, occurence + 1);
            }
        }
    }
    System.out.println(hashMap);
}

}

但是,它只打印所有赋值为 2 的字母。

在您的代码中出现的变量处理不正确。

单循环就足够了。见下文,您不需要使用额外的变量,只需根据键从地图本身获取现有计数。

for (int i = 0; i < array.length; i++) {
            char currentChar = hello.charAt(i);
            if(hashMap.containsKey(currentChar)) {
                hashMap.put(currentChar,hashMap.get(currentChar)+1);
            }else{
                hashMap.put(currentChar,1);
            }
        }

Java 版本 8 及更高版本带有许多强大的地图变异操作

    Map<Character,Integer> counts = new HashMap<>();

    for (char c : data.toCharArray())
    {
        counts.merge(c, 1, (oldValue,value)-> oldValue+1 );
    }

合并操作要么在映射中创建条目,要么将重新映射函数应用于旧值。 v1 是第二个参数的副本,以备重新映射时需要。在你的情况下不是,因为增量是一个常数。

这是一个例子:

String hello = "Hello there";
Map<Character, Integer> count = new HashMap<>();
for (char c : hello.toCharArray()) {
    count.compute(c, (ch, n) -> n == null ? 1 : n.intValue() + 1);
}
System.out.println(count);

它产生

{ =1, r=1, t=1, e=3, h=1, H=1, l=2, o=1}