THINK FIRST·CODE LATER

← All labs

Grouping with collectors

Problem

Write a class City (name, country, population in millions) and CityGroups, which reads name country millions lines and uses Collectors to print:

  1. country → list of city names (groupingBy with TreeMap::new and mapping),
  2. country → number of cities (counting),
  3. country → total population (summingDouble), one line per country,
  4. the megacities (≥ 10 million) and the others (partitioningBy),
  5. the country with the largest total (stream over entrySet() with max).

For the input

Shanghai China 24.9
Niamey Niger 1.4
Beijing China 21.5
Lagos Nigeria 15.4
Zinder Niger 0.5
Abuja Nigeria 3.8

the program prints

Cities: {China=[Shanghai, Beijing], Niger=[Niamey, Zinder], Nigeria=[Lagos, Abuja]}
Counts: {China=2, Niger=2, Nigeria=2}
  China: 46.4 million
  Niger: 1.9 million
  Nigeria: 19.2 million
Megacities: [Shanghai, Beijing, Lagos]
Others: [Niamey, Zinder, Abuja]
Most urban population: China

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-5-data-1.txt

Shanghai China 24.9
Niamey Niger 1.4
Beijing China 21.5
Lagos Nigeria 15.4
Zinder Niger 0.5
Abuja Nigeria 3.8
What your program must print for d3-5-data-1.txt
Cities: {China=[Shanghai, Beijing], Niger=[Niamey, Zinder], Nigeria=[Lagos, Abuja]}
Counts: {China=2, Niger=2, Nigeria=2}
  China: 46.4 million
  Niger: 1.9 million
  Nigeria: 19.2 million
Megacities: [Shanghai, Beijing, Lagos]
Others: [Niamey, Zinder, Abuja]
Most urban population: China

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-5-data-1.txt

Windows PowerShell does not understand <:

Get-Content d3-5-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.