← All Exercises
Top Three Words from Lines with Streams
intermediatejava
Background
Stream grouping and custom comparators are everyday Java skills. This exercise mirrors a small log or document summarizer in a few pipeline stages.
Problem
Given a list of text lines, return the three most frequent lowercase words of at least three letters, breaking count ties alphabetically.
Input
A non-null list of text lines with words separated by non-letter characters; comparison is case-insensitive and the limit must be positive.
Output
A list of word/count entries limited to three, ordered by count descending and then word ascending.
Sample tests
Sample 1
Input: The quick brown fox jumps over the lazy dog.; The dog barks; the fox runs.
Expected: the 4 dog 2 fox 2
Sample 2
Input: lines: 'Alpha beta beta'; 'gamma alpha alpha'
Expected: alpha 3 beta 2 gamma 1
Your solution
Learning objective
Use flatMap tokenization, groupingBy with counting, and a two-key comparator to produce a deterministic top-N.