Advertisement
Ligh7_of_H3av3n

09. Population Counter

May 21st, 2024
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. package Uprajnenie;
  2.  
  3. import java.util.LinkedHashMap;
  4. import java.util.Scanner;
  5.  
  6. public class PopulationCounter {
  7.     public static void main(String[] args) {
  8.         Scanner scanner = new Scanner(System.in);
  9.  
  10.  
  11.         String input = "";
  12.         LinkedHashMap<String , LinkedHashMap<String, Long>> countriesAndCities = new LinkedHashMap<>();
  13.         LinkedHashMap<String, Long> countriesOnly = new LinkedHashMap<>();
  14.  
  15.         // Read input until "report" is encountered
  16.         while(!(input = scanner.nextLine()).equals("report")){
  17.             String [] data = input.split("\\|");
  18.             String city = data[0];
  19.             String country = data[1];
  20.             Long population = Long.parseLong(data[2]);
  21.  
  22.             // If country is encountered for the first time, initialize its city map and population count
  23.             if(!countriesAndCities.containsKey(country)){
  24.                 countriesAndCities.put(country,new LinkedHashMap<>());
  25.                 countriesOnly.put(country, 0L);
  26.             }
  27.             // Update total population count for the country
  28.             countriesOnly.put(country,countriesOnly.get(country)+population);
  29.             // Add city population to the city map of the country
  30.             if(!countriesAndCities.get(country).containsKey(city)){
  31.                 countriesAndCities.get(country).put(city,population);
  32.             }
  33.         }
  34.  
  35.         // Sort countries by total population in descending order and print aggregated data
  36.         countriesAndCities.entrySet().stream()
  37.                 .sorted((c1,c2)-> countriesOnly.get(c2.getKey()).compareTo(countriesOnly.get(c1.getKey())))
  38.                 .forEach(country ->{
  39.                     System.out.format("%s (total population: %d)\n",country.getKey(),countriesOnly.get(country.getKey()));
  40.                     country.getValue().entrySet()
  41.                             .stream().sorted((t1,t2)-> t2.getValue().compareTo(t1.getValue())).forEach(city ->{
  42.                                 System.out.format("=>%s: %d\n", city.getKey(),city.getValue());
  43.                             });
  44.                 });
  45.  
  46.         scanner.close();
  47.     }
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement