Java How To - Character Frequency in a String
How To Count Character Frequency in a String
Use a HashMap
to count how many times each character appears:
Example
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
String text = "banana";
HashMap<Character, Integer> freq = new HashMap<>();
for (char c : text.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
System.out.println(freq);
// Output: {a=3, b=1, n=2}
}
}
Explanation:
We loop through each character in the string and use a HashMap
to keep track of counts.
- freq.getOrDefault(c, 0)
means "get the current count of this character, or 0 if it hasn't been seen yet."
- We then add 1 and put the new value back in the map.
For the string "banana"
, the result is {a=3, b=1, n=2}
.