Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Advance.SetsAndMaps.Exercise;
- import java.util.*;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class PopulationCounter {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- LinkedHashMap<String, LinkedHashMap<String, Integer>> countryMap = new LinkedHashMap<>();
- TreeMap<String, Integer> populationCounter = new TreeMap<>();
- String regex = "(?<city>[A-Za-z]+[\\s]?[A-Za-z]*)\\|(?<country>[A-Za-z\\s]*)\\|(?<population>[\\d]+)";
- Pattern pattern = Pattern.compile(regex);
- String input = scanner.nextLine();
- while (!"report".equals(input)) {
- Matcher matcher = pattern.matcher(input);
- while (matcher.find()) {
- String country = matcher.group("country");
- String city = matcher.group("city");
- int population = Integer.parseInt(matcher.group("population"));
- if (!countryMap.containsKey(country)) {
- countryMap.put(country, new LinkedHashMap<>());
- countryMap.get(country).put(city, population);
- populationCounter.put(country, population);
- } else {
- if (!countryMap.get(country).containsKey(city)) {
- countryMap.get(country).put(city, population);
- populationCounter.put(country, populationCounter.get(country) + population);
- } else {
- countryMap.get(country).put(city, population);
- populationCounter.put(country, populationCounter.get(country) + population);
- }
- }
- }
- input = scanner.nextLine();
- }
- List<Integer> descendingList = new ArrayList<>();
- for (Map.Entry<String, Integer> item : populationCounter.entrySet()) {
- descendingList.add(item.getValue());
- }
- descendingList.sort(Collections.reverseOrder());
- boolean printed = false;
- for (int i = 0; i < descendingList.size(); i++) {
- printed = false;
- for (Map.Entry<String, Integer> populationEntry : populationCounter.entrySet()) {
- String countryName = populationEntry.getKey();
- int countryPopulation = populationEntry.getValue();
- if (countryPopulation == descendingList.get(i)) {
- System.out.printf("%s (total population: %d)%n", countryName, countryPopulation);
- for (Map.Entry<String, LinkedHashMap<String, Integer>> countryEntry : countryMap.entrySet()) {
- if (countryName.equals(countryEntry.getKey())) {
- List<Integer> cityList = new ArrayList<>();
- for (Map.Entry<String, Integer> citySet : countryEntry.getValue().entrySet()) {
- cityList.add(citySet.getValue());
- }
- cityList.sort(Collections.reverseOrder());
- for (int j = 0; j < cityList.size(); j++) {
- for (Map.Entry<String, Integer> printCity : countryEntry.getValue().entrySet()) {
- if (printCity.getValue() == cityList.get(j)) {
- System.out.printf("=>%s %d%n", printCity.getKey(), printCity.getValue());
- }
- }
- }
- printed = true;
- }
- if (printed) {
- break;
- }
- }
- }
- if (printed) {
- break;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment