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.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d3-2-data-1.txt

The cat saw the other cat.
What your program must print for d3-2-data-1.txt
Words: 6
Distinct: [cat, other, saw, the]
Longest: other
By length: {3=5, 5=1}

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d3-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content d3-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

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.