veronikaaa86

Population Counter

Feb 16th, 2018
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. package MapLambdaStream;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.LinkedHashMap;
  7. import java.util.Map;
  8.  
  9. public class P07_PopulationCounter {
  10.     public static void main(String[] args) throws IOException {
  11.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  12.  
  13.         //Sofia|Bulgaria|1000000
  14.         //need calculate total population of Country
  15.  
  16.         String line = "";
  17.         Map<String, LinkedHashMap<String, Long>> map = new LinkedHashMap<>();
  18.         Map<String, Long> populations = new LinkedHashMap<>();
  19.  
  20.         while (!"report".equals(line = reader.readLine())) {
  21.             String[] input = line.split("\\|");
  22.  
  23.             String city = input[0];
  24.             String country = input[1];
  25.             long population = Integer.parseInt(input[2]);
  26.  
  27.             if (!map.containsKey(country)) {
  28.                 map.put(country, new LinkedHashMap<>());
  29.                 populations.put(country, 0L);
  30.             }
  31.             map.get(country).put(city, population);
  32.             long totalPopulation = populations.get(country);
  33.             populations.put(country, totalPopulation + population);
  34.         }
  35.         populations.entrySet()
  36.                 .stream()
  37.                 .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
  38.                 .forEach(entry -> {
  39.                     System.out.printf("%s (total population: %d)%n", entry.getKey(), entry.getValue());
  40.                     map.get(entry.getKey())
  41.                             .entrySet()
  42.                             .stream()
  43.                             .sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
  44.                             .forEach(pair -> {
  45.                                 System.out.printf("=>%s: %d%n", pair.getKey(), pair.getValue());
  46.                             });
  47.                 });
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment