Advertisement
ivanov_ivan

Population Counter

May 26th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. package exercise;
  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. import java.util.stream.Collectors;
  9.  
  10. public class Population {
  11.     public static void main(String[] args) throws IOException {
  12.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  13.  
  14.         Map<String, Map<String, Long>> data = new LinkedHashMap<>();
  15.  
  16.         String line;
  17.         while (!"report".equals((line = reader.readLine()))) {
  18.             String[] tokens = line.split("\\|");
  19.             String city = tokens[0];
  20.             String country = tokens[1];
  21.             Long population = Long.parseLong(tokens[2]);
  22.  
  23.             if (!data.containsKey(country)) {
  24.                 data.put(country, new LinkedHashMap<>());
  25.             }
  26.             data.get(country).put(city, population);
  27.         }
  28.  
  29.         data.entrySet().stream().sorted((c1, c2) -> Long.compare(c2.getValue().values().stream().collect(Collectors.summarizingLong(Long::valueOf)).getSum()
  30.                 , c1.getValue().values().stream().collect(Collectors.summarizingLong(Long::valueOf)).getSum())).forEach(country -> {
  31.             System.out.println(String.format("%s (total population: %d)", country.getKey(),
  32.                     country.getValue().values().stream().collect(Collectors.summarizingLong(Long::valueOf)).getSum()));
  33.             country.getValue().entrySet().stream().sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
  34.                     .forEach(pair -> System.out.println(String.format("=>%s: %d", pair.getKey(), pair.getValue())));
  35.         });
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement