How do I read specific values from a txt file and put them into a HashMap?

≡放荡痞女 提交于 2019-12-12 06:15:09

问题


I have a text file that looks like this:

a, 9, 1

b, 10, 5

c, 3, 4

etc...

I am trying to create two hashmaps where the keys in both are the letters, the values for the first map are the first number, and values for the second map are the second number. For example, Map1 = [a, 9, b, 10, c, 3] and Map2 = [a, 1, b, 5, c, 4]

I can't figure out how to access the specific character and matching integer. Here is what I have so far:

public static void constructLetterMaps() throws FileNotFoundException{
    File file2 = new File(fileLoc2);
    Scanner scan = new Scanner(file2);

    Map1 = new HashMap<Character, Integer>();
    Map2 = new HashMap<Character, Integer>();

    while(scan.hasNextLine())
    {
        Map1.put(scan.next(), scan.nextInt());
    }

}


回答1:


You could try this to populate the maps:

while(scan.hasNextLine())
{
    String key = (String) scan.next();
    Map1.put(key, scan.nextInt());
    Map2.put(key, scan.nextInt());
}

To access a single key, use hashmap.get(key).

To access the key or entry set as a whole, check out hashmap.entrySet() and keySet() methods



来源:https://stackoverflow.com/questions/29837331/how-do-i-read-specific-values-from-a-txt-file-and-put-them-into-a-hashmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!