Home  >  Article  >  Java  >  How to Efficiently Count Character Frequency in a String?

How to Efficiently Count Character Frequency in a String?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 19:24:30878browse

How to Efficiently Count Character Frequency in a String?

Determining Character Frequency in Strings

Counting the frequency of characters in a string is a common task in programming. To achieve this, consider the following question:

Question: How does one efficiently count character frequency in a string?

Answer: To determine character frequency, create a Java Map that maps characters to integers. Iterate through the string's characters and check if they exist in the map. If so, increment their value; otherwise, initialize their value to 1.

Map<Character, Integer> map = new HashMap<>();
String s = "aasjjikkk";

for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    Integer val = map.get(c);
    if (val != null) {
        map.put(c, val + 1);
    } else {
        map.put(c, 1);
    }
}

This method will result in a map with characters as keys and their respective frequencies as values.

Alternatively, you could utilize Bozho's suggestion of using a Multiset to count character occurrences directly.

The above is the detailed content of How to Efficiently Count Character Frequency in a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn