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

How to Efficiently Count Character Frequencies in a String?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 07:21:30648browse

How to Efficiently Count Character Frequencies in a String?

Counting Character Frequency in Strings

A common task in programming is counting the frequency of characters in a given string. Suppose we have a string "aasjjikkk." We want to determine the count of each unique character, resulting in "2 'a', 1 's', 2 'j', 1 'i', 3 'k'."

Solution Using Java Map

One efficient solution is to utilize a Java Map, which associates keys (in this case, characters) with values (the count of their occurrences). We traverse the string and check if each character is already in the map. If it is, we increment its count; otherwise, we insert it with a count of 1.

<code class="java">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 approach provides a natural representation of the character counts in a key-value pair format.

Alternative Solution Using Multiset

Alternatively, Guava's Multiset data structure allows us to count the occurrences of elements without explicitly maintaining a map.

<code class="java">Multiset<Character> multiset = HashMultiset.create();
String s = "aasjjikkk";
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    multiset.add(c);
}</code>

The multiset now holds the counts of each character in the string.

The above is the detailed content of How to Efficiently Count Character Frequencies 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