THINK FIRST·CODE LATER

← All labs

Word statistics with streams

Problem

Read one line of text and summarise its words using streams and collectors.

A word is a maximal run of letters A–Z/a–z; everything else separates words. Convert every word to lower case before processing. The line may be empty or contain no letters at all.

Print exactly four lines:

  1. Words: and the number of words;
  2. Distinct: and the distinct words in alphabetical order, as [w1, w2, …] ([] when there are none);
  3. Longest: and the longest word — if several share the maximum length, the alphabetically first — or none;
  4. By length: and a map from word length to number of words, keys in increasing order, printed with the map's toString (e.g. {3=5, 5=1}, or {}).
Input:
The cat saw the other cat.

Output:
Words: 6
Distinct: [cat, other, saw, the]
Longest: other
By length: {3=5, 5=1}

Hint: line.split("[^A-Za-z]+") can produce an empty first element, so filter it out.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.