Advertisement
Guest User

10.

a guest
Jan 4th, 2022
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. package SetsAndMapsAdvanced;
  2.  
  3. import java.lang.reflect.Array;
  4. import java.util.*;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7.  
  8. public class EXR_PopulationCounter {
  9. public static void main(String[] args) {
  10. Scanner scanner = new Scanner(System.in);
  11.  
  12. String input = scanner.nextLine();
  13.  
  14. LinkedHashMap<String, List<CityData>> populationMap = new LinkedHashMap<>();
  15.  
  16. Pattern pattern = Pattern.compile("(?<city>.+)\\|(?<country>.+)\\|(?<population>.+)");
  17.  
  18. String country = "";
  19. String city = "";
  20. int population = 0;
  21.  
  22.  
  23. while(!input.equals("report")){
  24. Matcher matcher = pattern.matcher(input);
  25. while(matcher.find()){
  26. country = matcher.group("country");
  27. city = matcher.group("city");
  28. population = Integer.parseInt(matcher.group("population"));
  29. }
  30.  
  31. CityData cityData = new CityData(city,population);
  32.  
  33. if (populationMap.containsKey(country)) {
  34. populationMap.get(country).add(cityData);
  35. }else{
  36. populationMap.put(country, new ArrayList<>());
  37. populationMap.get(country).add(cityData);
  38. }
  39.  
  40. input = scanner.nextLine();
  41. }
  42.  
  43. populationMap.entrySet().stream()
  44. .sorted((e1,e2)-> Integer.compare(getTotalPopulation(e2),getTotalPopulation(e1)))
  45. .forEach(e->{
  46. System.out.println(e.getKey() + " (total population: " + getTotalPopulation(e) + ")");
  47. List<CityData>currentList = e.getValue();
  48. currentList.stream().sorted(Comparator.comparing(CityData::getPopulation).reversed()).forEach(el->{
  49. System.out.println("=>" + el.getCity() + ": " + el.getPopulation());
  50. });
  51. });
  52. }
  53.  
  54. private static int getTotalPopulation(Map.Entry<String, List<CityData>> e) {
  55. List<CityData> current = e.getValue();
  56. int result = 0;
  57. for (CityData data:current) {
  58. result += data.getPopulation();
  59. }
  60. return result;
  61. }
  62.  
  63. public static class CityData{
  64. private String city;
  65. private int population;
  66.  
  67. public CityData(String city, int population) {
  68. this.city = city;
  69. this.population = population;
  70. }
  71.  
  72. public String getCity() {
  73. return city;
  74. }
  75.  
  76. public int getPopulation() {
  77. return population;
  78. }
  79. }
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement