bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To - Character Frequency in a String

Flash cards

Review the key moves

1/4
Core idea

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.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ java.util.HashMap;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Explanation: We loop through each character in the string and use a HashMap to keep track of counts.
Use a HashMap to count how many times each character appears:
How To Count 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} .

Previous

Java How To - Remove Whitespace from a String

Next

Java How To Calculate the Sum of Elements