Advertisement
desislava_topuzakova

10. Population Counter

Jan 18th, 2022
1,178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.concurrent.atomic.AtomicReference;
  3.  
  4. public class LiveDemo {
  5.     public static void main(String[] args) {
  6.         Scanner scanner = new Scanner(System.in);
  7.  
  8.         String input = scanner.nextLine();
  9.  
  10.         LinkedHashMap<String, LinkedHashMap<String, Long>> populationByCountries = new LinkedHashMap<>();
  11.  
  12.         while (!input.equals("report")){
  13.  
  14.             String[] tokens = input.split("\\|");
  15.  
  16.             String city = tokens[0];
  17.             String country = tokens[1];
  18.             Long population = Long.parseLong(tokens[2]);
  19.  
  20.             if(!populationByCountries.containsKey(country)){
  21.                 populationByCountries.put(country, new LinkedHashMap<>(){{
  22.                     put(city, population);
  23.                 }});
  24.             }else{
  25.                 populationByCountries.get(country).put(city, population);
  26.             }
  27.  
  28.             input = scanner.nextLine();
  29.         }
  30.  
  31.         populationByCountries.entrySet().stream().sorted((e1, e2) -> {
  32.                    Long totalPopulationFirst = populationByCountries.get(e1.getKey()).entrySet().stream().mapToLong(Map.Entry::getValue).sum();
  33.                    Long totalPopulationSecond = populationByCountries.get(e2.getKey()).entrySet().stream().mapToLong(Map.Entry::getValue).sum();
  34.                    return Long.compare(totalPopulationSecond, totalPopulationFirst);
  35.         }).forEach(entry -> {
  36.             System.out.print(entry.getKey() + " ");
  37.  
  38.             StringBuilder builder = new StringBuilder();
  39.  
  40.             AtomicReference<Long> totalPopulation = new AtomicReference<>((long) 0);
  41.  
  42.             populationByCountries.get(entry.getKey()).entrySet().stream().sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
  43.                     .forEach(e -> {
  44.                         builder.append(String.format("=>%s: %d%n", e.getKey(), e.getValue()));
  45.                         totalPopulation.updateAndGet(v -> v + e.getValue());
  46.                     });
  47.  
  48.             System.out.println(String.format("(total population: %s)", totalPopulation.toString()));
  49.             System.out.print(builder.toString());
  50.         });
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement