borovaneca

Citizen

Feb 21st, 2023
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. package Advance.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.  
  10.         int rotation = Integer.parseInt(scanner.nextLine());
  11.         LinkedHashMap<String, LinkedHashMap<String, List<String>>> continentMap = new LinkedHashMap<>();
  12.  
  13.         for (int i = 0; i < rotation; i++) {
  14.             String[] commandArr = scanner.nextLine().split("\\s+");
  15.             String continent = commandArr[0];
  16.             String country = commandArr[1];
  17.             String city = commandArr[2];
  18.  
  19.             if (!continentMap.containsKey(continent)) {
  20.                 continentMap.put(continent, new LinkedHashMap<>());
  21.                 continentMap.get(continent).put(country, new ArrayList<>());
  22.                 continentMap.get(continent).get(country).add(city);
  23.             } else {
  24.                 if (!continentMap.get(continent).containsKey(country)){
  25.                     continentMap.get(continent).put(country, new ArrayList<>());
  26.                     continentMap.get(continent).get(country).add(city);
  27.                 } else {
  28.                     continentMap.get(continent).get(country).add(city);
  29.                 }
  30.             }
  31.         }
  32.  
  33.         for (Map.Entry<String, LinkedHashMap<String, List<String>>> continent : continentMap.entrySet()) {
  34.             System.out.printf("%s:%n", continent.getKey());
  35.             for (Map.Entry<String, List<String>> country : continent.getValue().entrySet()) {
  36.                 System.out.printf("  %s -> ", country.getKey());
  37.                 System.out.print(String.join(", ", country.getValue()));
  38.                 System.out.println();
  39.             }
  40.  
  41.         }
  42.  
  43.     }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment