Advertisement
Didart

Cities by Continent and Country

Jan 19th, 2023 (edited)
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. package SetsAndMaps;
  2.  
  3. import java.util.*;
  4.  
  5. public class CitiesByContinentAndCountry {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.        
  9.         int number = Integer.parseInt(scanner.nextLine());
  10.  
  11.         Map<String, Map<String, List<String>>> nestedMap = new LinkedHashMap<>();
  12.  
  13.         for (int index = 0; index < number; index++) {
  14.             String[] tokens = scanner.nextLine().split("\\s+");
  15.             String continent = tokens[0];
  16.             String country = tokens[1];
  17.             String city = tokens[2];
  18.  
  19.             nestedMap.putIfAbsent(continent, new LinkedHashMap<>());
  20.  
  21.             if (nestedMap.containsKey(continent)) {
  22.                 nestedMap.get(continent).putIfAbsent(country, new ArrayList<>());
  23.  
  24.                 if (nestedMap.get(continent).containsKey(country)) {
  25.                     nestedMap.get(continent).get(country).add(city);
  26.                 }
  27.             }
  28.         }
  29.         System.out.println();
  30.         nestedMap.forEach((key, value) -> {
  31.  
  32.             System.out.printf("%s:%n",key);
  33.  
  34.             for (Map.Entry<String, List<String>> country : value.entrySet()) {
  35.                 System.out.printf("%s -> ", country.getKey());
  36.                 for (int i = 0; i < country.getValue().size(); i++) {
  37.                     System.out.printf("%s", country.getValue().get(i));
  38.                     if (i < country.getValue().size() - 1) {
  39.                         System.out.print(", ");
  40.                     }
  41.                 }
  42.                 System.out.println();
  43.             }
  44.         });
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement