Flash cards
Review the key moves
What is the main idea behind Java How To - Character Frequency in a String?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ java.util.HashMap;Put the learning moves in the order that makes the concept easiest to apply.
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} .