将文件读入哈希映射问题

时间:2017-03-19 15:41:17

标签: java csv hashmap

我在尝试将大量数据加载到不同的hashMaps时遇到了麻烦。我使用一个不同的类来处理文件的所有解码并转移到hashMap。我的问题是我将一个文件加载到一个特定的hashMap(比如hashMap x)。但是当我需要将不同的数据加载到ex。 hasMap y,hashMap x被重写为hashMap y应该拥有的所有东西。我后来发现一些键和值是从不同的文件中传来的,但是有些键被删除了,因为hashMap不允许重复。所以我对x和y的最终结果是将两个文件的数据混合到一个hashMap中。我不知道如何解决这个问题。

这是我到目前为止所做的:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CodeFileProcessor {

    private static Map<String, String> codeMap = new HashMap<String, String>();

    public static Map<String, String> readCodeFile(String fileName) throws  IOException {
        codeMap.clear();
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String nextLine = br.readLine();
        while(nextLine != null) {
            String[] parts = nextLine.split(",");
            codeMap.put(parts[0], parts[1]);
            nextLine = br.readLine();
        }
    br.close();
    return codeMap;
    }
}

1 个答案:

答案 0 :(得分:0)

您的问题看起来像codeMap是静态的。你基本上重复使用相同的地图,这就是为什么事情看起来会被覆盖。

尝试在方法调用中创建新地图:

//DELETE THIS LINE - private static Map<String, String> codeMap = new HashMap<String, String>();

public static Map<String, String> readCodeFile(String fileName) throws  IOException {
    //Create a new map instead of reusing the static (shared) one
    Map<String, String> codeMap = new HashMap<String, String>();
        ...