Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class PopulationCounter {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String command;
- Map<String, Country> countries = new TreeMap<>();
- while (!"report".equals(command = scanner.nextLine())) {
- String[] countryTokens = command.split("\\|");
- String cityName = countryTokens[0];
- String countryName = countryTokens[1];
- int population = Integer.valueOf(countryTokens[2]);
- Country country = new Country(countryTokens[1]);
- if (!countries.containsKey(countryName)) {
- country.cities.put(cityName, population);
- country.population = population;
- countries.put(countryName, country);
- } else {
- for (Map.Entry<String, Country> countryKey : countries.entrySet()) {
- if (countryName.equals(countryKey.getKey())) {
- countryKey.getValue().cities.put(cityName, population);
- countryKey.getValue().addPopulation(population);
- countries.put(countryName, countryKey.getValue());
- }
- }
- }
- }
- for (Map.Entry<String, Country> country : countries.entrySet()) {
- System.out.printf("%s (total population: %d)%n", country.getKey(), country.getValue().population);
- for (Map.Entry<String, Integer> city : country.getValue().cities.entrySet()) {
- System.out.printf("=>%s: %d%n", city.getKey(), city.getValue());
- }
- }
- }
- private static class Country {
- public String name;
- public Map<String, Integer> cities;
- public int population;
- public Country() {
- }
- public Country(String name) {
- this.name = name;
- this.cities = new LinkedHashMap<>();
- }
- public void addPopulation(int population) {
- this.population += population;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment