Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Uprajnenie;
- import java.util.LinkedHashMap;
- import java.util.Scanner;
- public class PopulationCounter {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String input = "";
- LinkedHashMap<String , LinkedHashMap<String, Long>> countriesAndCities = new LinkedHashMap<>();
- LinkedHashMap<String, Long> countriesOnly = new LinkedHashMap<>();
- // Read input until "report" is encountered
- while(!(input = scanner.nextLine()).equals("report")){
- String [] data = input.split("\\|");
- String city = data[0];
- String country = data[1];
- Long population = Long.parseLong(data[2]);
- // If country is encountered for the first time, initialize its city map and population count
- if(!countriesAndCities.containsKey(country)){
- countriesAndCities.put(country,new LinkedHashMap<>());
- countriesOnly.put(country, 0L);
- }
- // Update total population count for the country
- countriesOnly.put(country,countriesOnly.get(country)+population);
- // Add city population to the city map of the country
- if(!countriesAndCities.get(country).containsKey(city)){
- countriesAndCities.get(country).put(city,population);
- }
- }
- // Sort countries by total population in descending order and print aggregated data
- countriesAndCities.entrySet().stream()
- .sorted((c1,c2)-> countriesOnly.get(c2.getKey()).compareTo(countriesOnly.get(c1.getKey())))
- .forEach(country ->{
- System.out.format("%s (total population: %d)\n",country.getKey(),countriesOnly.get(country.getKey()));
- country.getValue().entrySet()
- .stream().sorted((t1,t2)-> t2.getValue().compareTo(t1.getValue())).forEach(city ->{
- System.out.format("=>%s: %d\n", city.getKey(),city.getValue());
- });
- });
- scanner.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement