Advertisement
damesova

Population Counter [Mimi][JA]

May 2nd, 2019
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. import java.util.LinkedHashMap;
  2. import java.util.Map;
  3. import java.util.Scanner;
  4. import java.util.stream.Collectors;
  5.  
  6. public class _10_PopulationCounter {
  7.     public static void main(String[] args) {
  8.         Scanner sc = new Scanner(System.in);
  9.         // Country=>    City,   Population
  10.         Map<String, Map<String, Long>> countries = new LinkedHashMap<>();
  11.  
  12.         String input = "";
  13.         while (!"report".equals(input = sc.nextLine())) {
  14.             String[] data = input.split("\\|");
  15.  
  16.             countries.putIfAbsent(data[1], new LinkedHashMap<>());
  17.             Map<String, Long> cities = countries.get(data[1]);
  18.             cities.putIfAbsent(data[0], 0L);
  19.             cities.put(data[0], cities.get(data[0]) + Long.parseLong(data[2]));
  20.         }
  21.  
  22.         countries
  23.                 .entrySet()
  24.                 .stream()
  25.                 .sorted((p1, p2) -> {
  26.                     long pop1 = p1.getValue()
  27.                             .values()
  28.                             .stream()
  29.                             .mapToLong(Long::valueOf)
  30.                             .sum();
  31.                     long pop2 = p2.getValue()
  32.                             .values()
  33.                             .stream()
  34.                             .mapToLong(Long::valueOf)
  35.                             .sum();
  36.                     return Long.compare(pop2, pop1);
  37.                 })
  38.                 .forEach(e -> {
  39.                     long pop = e.getValue().values().stream().mapToLong(Long::longValue).sum();
  40.                     System.out.println(String.format("%s (total population: %d)", e.getKey(), pop));
  41.  
  42.                     Map<String, Long> sortedCities = e.getValue()
  43.                             .entrySet()
  44.                             .stream()
  45.                             .sorted((c1, c2) -> Long.compare(c2.getValue(), c1.getValue()))
  46.                             .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));
  47.                     sortedCities.forEach((key, value) -> System.out.println(String.format("=>%s: %d", key, value)));
  48.                 });
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement