简体   繁体   English

将文件中的值添加到带有Map的HashMap中

[英]Adding values from a file to a HashMap with a Map inside

I'm trying to read from a package of txt files and adding the values to my HashMap. 我正在尝试从txt文件包中读取内容并将这些值添加到我的HashMap中。 I'm trying to split the values using split(","). 我正在尝试使用split(“,”)拆分值。 Then depending if the gender value is F or M to add to the right Map. 然后根据性别值是F还是M添加到正确的地图。

girlsByYear.put(number, (name, value)); girlsByYear.put(数字,(名称,值)); This code gives me a compile error saying "The Field String.value is not visible", which I don't understand because it seems to be able to see number and name. 这段代码给我一个编译错误,说“字段String.value不可见”,我不明白,因为它似乎可以看到数字和名称。 I'm also new to using HashMaps and other sorts of Sets. 我也是使用HashMaps和其他Sets的新手。 I'm not even sure if that is the right syntax to put values into a map inside of a HashMap. 我什至不确定这是否是将值放入HashMap内的映射的正确语法。

These are the HashMaps I'm using: 这些是我正在使用的HashMap:

HashMap<String, Map<String, Integer>> girlsByYear = new HashMap<String, Map<String, Integer>>();
HashMap<String, Map<String, Integer>> boysByYear = new HashMap<String, Map<String, Integer>>();

public void load() throws FileNotFoundException {

    File dir = new File("src/data");
    File [] files = dir.listFiles();

    // for each file in the directory...
    for (File f : files)
    {   
        Scanner input = new Scanner(f);
        while (input.hasNext()) {

              String line = input.next();
              String [] details = line.split(",");

              String name = details[0];
              String gender = details[1];
              String value = details[2];

              if(gender == "F") {
                  girlsByYear.put(number, (name, value));
              }
              else {
                  boysByYear.put(number, (name, value));
              }

            }

        number++;

    }
}

First you need to check if the nested map exists and if not, create it. 首先,您需要检查嵌套地图是否存在,如果不存在,请创建它。 Then you can add the value by retrieving the nested map and putting an object inside of that map. 然后,您可以通过检索嵌套地图并将对象放入该地图中来添加值。 eg: 例如:

if (!girlsByYear.containsKey(number)) {
    girlsByYear.put(number, new HashMap<>());
}
girlsByYear.get(number).put(name, value);

I want to improve @flake answer, if you use Java 8 you can you this: 我想改善@flake答案,如果您使用Java 8,可以这样做:

girlsByYear.putIfAbsent(number, new HashMap<>());
girlsByYear.get(number).put(name, value);

Or you can try Guava library (a widely used library from Google), it has a data structure called Table: 或者,您可以尝试使用Guava库(Google广泛使用的库),它具有名为Table的数据结构:

Table<String, String, Integer> girlsByYear = HashBasedTable.create();
//...
girlsByYear.put(number, name, value);

You can check tutorial how to use Table here https://www.baeldung.com/guava-table 您可以在这里查看教程如何使用表格https://www.baeldung.com/guava-table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM