Java Streams learning path Level 1 This level · 14 of 25
Easy java streams

Count character frequency in a string

The 30 second answer

I turn the string into a stream of characters and collect with groupingBy and counting. That gives a map from character to frequency. Before coding I clarify case folding and whitespace, and whether they care about code points versus UTF-16 chars for non-BMP text.

Could you say this in an interview?
Map<Character, Long> freq = s.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Same codePoints() caveat as the first-non-repeated problem. Decide on case-folding and whitespace before coding.

Sources (2)
  1. Collectors.countingdocs.oracle.com
  2. CharSequencedocs.oracle.com
Previous
Next