LardaX

PopulationCounterStream

Jan 25th, 2017
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class PopulationCounterShorter {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.         LinkedHashMap<String, HashMap<String, Long>> countries = new LinkedHashMap<>();
  7.  
  8.         while (true) {
  9.             String[] input = scanner.nextLine().split("\\|");
  10.  
  11.             if ("report".equals(input[0])) {
  12.                 break;
  13.             }
  14.  
  15.             String city = input[0];
  16.             String country = input[1];
  17.             Long population = Long.parseLong(input[2]);
  18.  
  19.             insertCountry(countries, country);
  20.             insertCity(countries, country, city, population);
  21.         }
  22.  
  23.         Map<String, Long> countriesByPopulation = new LinkedHashMap<>();
  24.  
  25.         for (String country : countries.keySet()) {
  26.             long totalPopulation = 0;
  27.             for (Long populationCount : countries.get(country).values()) {
  28.                 totalPopulation += populationCount;
  29.             }
  30.             countriesByPopulation.put(country, totalPopulation);
  31.         }
  32.  
  33.         countriesByPopulation.entrySet().stream()
  34.                 .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
  35.                 .forEach(entry -> {
  36.                     System.out.println(entry.getKey() + " (total population: " + entry.getValue() + ")");
  37.                     countries.get(entry.getKey()).entrySet().stream()
  38.                             .sorted(Map.Entry.comparingByValue((v1, v2) -> v2.compareTo(v1)))
  39.                             .forEach(pair -> {
  40.                                 System.out.println("=>" + pair.getKey() + ": " + pair.getValue());
  41.                             });
  42.                 });
  43.     }
  44.  
  45.  
  46.     private static void insertCity(LinkedHashMap<String, HashMap<String, Long>> countries, String country, String city, Long population) {
  47.         if (!countries.get(country).containsKey(city)) {
  48.             countries.get(country).put(city, population);
  49.         }
  50.     }
  51.  
  52.     private static void insertCountry(LinkedHashMap<String, HashMap<String, Long>> countries, String country) {
  53.         if (!countries.containsKey(country)) {
  54.             countries.put(country, new LinkedHashMap<>());
  55.         }
  56.     }
  57. }
Add Comment
Please, Sign In to add comment