Java and Spring Level 1 This level · 23 of 105
Easy java streams

Count word frequency in a sentence

The 30 second answer

I lower-case the text, split on non-word characters, drop blanks, and group with counting. In the interview I clarify tokenization: punctuation, apostrophes, and Unicode letters. Plain W is ASCII-only unless the Unicode character class flag is on.

Could you say this in an interview?
Map<String, Long> wf = Arrays.stream(text.toLowerCase().split("\\W+"))
    .filter(w -> !w.isBlank())
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Clarify tokenization (punctuation, apostrophes, Unicode letters). \W is ASCII-only unless UNICODE_CHARACTER_CLASS is used. Alternative: Pattern.compile("\\W+").splitAsStream(text).

Sources (2)
  1. Collectorsdocs.oracle.com
  2. Patterndocs.oracle.com
Previous
Next