Advertisement
Ivakis

Population Count

Oct 3rd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. package P14_PopulationCounter;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.*;
  7. import java.util.stream.Collectors;
  8.  
  9. public class Main {
  10. public static void main(String[] args) throws IOException {
  11. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  12.  
  13. HashMap<String, HashMap<String, Long>> populationStrore = new HashMap<>();
  14.  
  15. String[] input = reader.readLine().split("\\|");
  16.  
  17. while (!input[0].equals("report")) {
  18.  
  19. String country = input[1];
  20. String city = input[0];
  21. Long population = Long.parseLong(input[2]);
  22.  
  23. populationStrore.putIfAbsent(country, new LinkedHashMap<>());
  24. populationStrore.get(country).putIfAbsent(city, population);
  25.  
  26. input = reader.readLine().split("\\|");
  27. }
  28. LinkedHashMap<String, Long> result = new LinkedHashMap<>();
  29.  
  30. for (String s : populationStrore.keySet()) {
  31. LinkedHashMap<String, Long> sorted = populationStrore.get(s).entrySet().stream()
  32. .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
  33. .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
  34.  
  35. Long totalPopulation = 0L;
  36. String towns = "";
  37. for (String s1 : sorted.keySet()) {
  38. Long townPop = populationStrore.get(s).get(s1);
  39. totalPopulation += townPop;
  40. towns += "=>" + s1 + ": " + townPop + "\n";
  41. }
  42. towns = s + " (total population: " + totalPopulation + ")" + "\n" + towns.substring(0, towns.length() - 1);
  43. result.put(towns, totalPopulation);
  44.  
  45. }
  46. LinkedHashMap<String, Long> sorted = result.entrySet().stream()
  47. .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
  48. .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
  49.  
  50. for (String s : sorted.keySet()) {
  51. System.out.println(s);
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement