Java嵌套的hashmaps内部hashmap在readfile期间被覆盖

时间:2016-10-19 21:10:01

标签: java hashmap nested

从我的硬盘驱动器中读取csv文件,并尝试根据世界银行的不同指标创建国家/地区的嵌套hashMap和键/值的内部hashMap。外部地图似乎工作正常,但内部地图存在更换所有外部键的数据与最后一个国家/地区数据的问题。这是我的代码:

public static HashMap<String, HashMap<String, Float>> loadPoliticalStabilityFromCSV(PApplet p, String filename){
    // HashMap key: country ID and data: some political stability measure
    HashMap<String, HashMap<String, Float>> countryDataMap = new HashMap<>();
    HashMap<String, Float> metricsMap = new HashMap<>();

    // pull in the lines from the csv file
    String[] rows = p.loadStrings(filename);
    // Reads country name from CSV row
    for (String row : rows){            

        // split row by commas not in quotations                    
        String[] columns = row.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
        // Grab Data Point
        for (int i = columns.length -1; i > 3; i--){
            if(!columns[i].equals(null)){
                metricsMap.put(columns[2], Float.parseFloat(columns[i]));
                countryDataMap.put(columns[1], metricsMap);
                break;
            }

        }


    }
    return countryDataMap;
}

我一直在阅读有关嵌套哈希映射的各种帖子,但解决方案正在逐渐掌握。任何帮助将不胜感激。我知道这需要在我的for循环中创建新的Hashmaps,但是当我这样做时,我最终只为每个外键抓取一个嵌套的键/值数据点(1行)。

2 个答案:

答案 0 :(得分:0)

您只使用一个内部HashMap(metricsMap),并且您只需将这一个地图放入countryDataMap。您应该为每个外键创建一个新的HashMap作为值。在将新HashMap放入外部映射之前,应检查是否已存在该密钥的内部HashMap并重用此密钥。像这样:

HashMap<String, Float> metricsMap;
if (countryDataMap.containsKey(columns[1]) {
    metricsMap = countryDataMap.get(columns[1]);
}
else {
    metricsMap = new HashMap<>();
}
// use metricsMap

或更简洁(尽管简洁并不总是更好的可读性):

HashMap<String, Float> metricsMap = countryDataMap.containsKey(columns[1]) ? countryDataMap.get(columns[1]) : new HashMap<>();

答案 1 :(得分:0)

谢谢大家。当你回答的时候,我一直在寻找,并让它与之合作。 (现在我回过头来看看你指出Oleg的东西。谢谢!

public static HashMap<String, HashMap<String, Float>> loadPoliticalStabilityFromCSV(PApplet p, String filename){
    // HashMap key: country ID and data: some political stability measure
    HashMap<String, HashMap<String, Float>> countryDataMap = new HashMap<>();
    //HashMap<String, Float> metricsMap = new HashMap<>();

    // pull in the lines from the csv file
    String[] rows = p.loadStrings(filename);
    // Reads country name from CSV row
    for (String row : rows){            

        // split row by commas not in quotations                    
        String[] columns = row.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
        // Grab Data Point
        for (int i = columns.length -1; i > 3; i--){
            HashMap<String, Float> inner = countryDataMap.get(columns[1]);
            if (inner == null){
                inner = new HashMap<>();
                countryDataMap.put(columns[1], inner);
            }
            inner.put(columns[2], Float.parseFloat(columns[i]));
            break;              

        }


    }
    return countryDataMap;
}
相关问题