首页 > 解决方案 > 如何将 hashmap 键(国家名称)与从 CSV 文件中检索的国家名称进行比较?

问题描述

我想根据每个国家/地区的武汉病例数就我的热图代码寻求一些意见或帮助,代码如下所示。

目前,我已将所有国家/地区坐标存储在哈希图中,并从https://www.worldometers.info/coronavirus/中提取数据,将国家名称和病例数存储在 CSV 文件中。

我正在尝试将 CSV 文件中的国家/地区名称与哈希图中的国家/地区名称(键)进行比较,这样如果存在这样的国家/地区,则在地图上绘制“热区”。但是,目前,当我尝试使用 if-else 语句进行比较时,如我的代码中所示。但是,我面临的问题是,如果 csv 文件缺少 1 个国家并且与 hashmap 不匹配,则代码将无法运行。只有当 csv 文件包含所有国家/地区名称并且它与 hashmap 匹配时,代码才会显示应用程序,如下所示。在比较 csv 文件和 hashmap 中的国家名称时,如何绘制“热区”?

代码

 @Override public void init() {

    //Input the coordinates of the country, based on the size of the javafx.
    //Limitation is the current coordinates are not the entire list of country in the world.
    HashMap<String, List<Integer>> countryCoordinates = new HashMap<>();
    Integer[] coordinates = {};
    countryCoordinates.put("China", Arrays.asList(700, 180));
    countryCoordinates.put("Diamond Princess", Arrays.asList(810, 170));
    countryCoordinates.put("Singapore", Arrays.asList(726, 310));
    countryCoordinates.put("Japan", Arrays.asList(810, 170));
    countryCoordinates.put("Hong Kong", Arrays.asList(755, 225));
    countryCoordinates.put("Thailand", Arrays.asList(720, 250));
    countryCoordinates.put("S. Korea", Arrays.asList(780, 170));
    countryCoordinates.put("Taiwan", Arrays.asList(775, 220));
    countryCoordinates.put("Malaysia", Arrays.asList(725, 300));
    countryCoordinates.put("Germany", Arrays.asList(440, 115));
    countryCoordinates.put("Vietnam", Arrays.asList(740, 260));
    .
    .
    .

    Reader reader;
    try {
        //Retrieving the data from WorldMap CSV
        reader = Files.newBufferedReader(Paths.get("C:\\Users\\User\\Desktop\\ICT1009_TESTFILE\\WorldMap.csv"));
        CSVReader csvReader = new CSVReader(reader);
        String[] nextRecord;
        while((nextRecord = csvReader.readNext()) != null) {
            String retrieveCountry = nextRecord[0];
            //Comparing the hashmap key with the country name retrieve from CSV file
            //If the names matches, plot the heat area
            List<Integer> coordinatesOfThisCountry = countryCoordinates.get(retrieveCountry);
            if (coordinatesOfThisCountry != null) {
                    events = new Point2D[] {
                            asPoint2D(countryCoordinates.get(retrieveCountry)),
                    };
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

输出 在此处输入图像描述

标签: javajavafx

解决方案


外循环必须逐行读取 CSV 文件,内循环必须与地图进行比较。但是,映射的目的是通过哈希码查找而不是 for 循环更快地找到匹配的条目。所以只剩下外循环:

while((nextRecord = csvReader.readNext()) != null) 
{
    String retrieveCountry = nextRecord[0];
    String retrieveCases = nextRecord[1];

    // Find the existing country in the map
    List<Integer> coordinatesOfThisCountry=countryCoordinates.get(retrieveCountry);

    if (coordinatesOfThisCountry!=null)
    {
        // found
        // TODO: plot the "heat area" 
    }
    else
    {
       // not found
    }
}

推荐阅读