Advertisement
svephoto

Population Counter [Java]

Jan 4th, 2022
1,178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.*;
  5.  
  6. public class PopulationCounter {
  7.     public static void main(String[] args) throws IOException {
  8.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  9.  
  10.         Map<String, Long> countriesAndTotalPopulation = new LinkedHashMap<>();
  11.         Map<String, Map<String, Long>> citiesAndTheirPopulation = new LinkedHashMap<>();
  12.  
  13.         String command;
  14.  
  15.         while (!"report".equals(command = reader.readLine())) {
  16.             String[] inputData = command.split("\\|");
  17.  
  18.             String city = inputData[0];
  19.             String country = inputData[1];
  20.             long population = Long.parseLong(inputData[2]);
  21.  
  22.             if (!countriesAndTotalPopulation.containsKey(country)) {
  23.                 countriesAndTotalPopulation.put(country, population);
  24.             } else {
  25.                 countriesAndTotalPopulation.put(country, countriesAndTotalPopulation.get(country) + population);
  26.             }
  27.  
  28.             if (!citiesAndTheirPopulation.containsKey(country)) {
  29.                 citiesAndTheirPopulation.put(country, new LinkedHashMap<>());
  30.                 citiesAndTheirPopulation.get(country).put(city, population);
  31.             } else {
  32.                 citiesAndTheirPopulation.get(country).put(city, population);
  33.             }
  34.         }
  35.  
  36.         countriesAndTotalPopulation.entrySet().stream()
  37.                 .sorted(Map.Entry.<String, Long>comparingByValue()
  38.                 .reversed())
  39.                 .forEach(currentCountry -> {
  40.                     System.out.printf("%s (total population: %d)%n",
  41.                             currentCountry.getKey(), currentCountry.getValue());
  42.  
  43.                     citiesAndTheirPopulation.get(currentCountry.getKey()).entrySet().stream()
  44.                             .sorted(Map.Entry.<String, Long>comparingByValue()
  45.                             .reversed())
  46.                             .forEach(city -> System.out.printf("=>%s: %d%n", city.getKey(), city.getValue()));
  47.                 });
  48.     }
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement