java将hashmap作为avalue添加到hashmap中
在下面的代码中,我创建了一个temp hashmap并将其作为值添加到另一个hashmap,在while循环的末尾,csvList hashmap只有temp has map作为值添加的最后一个值,所有其他值都为null
该键将被保留,所有值均替换为null。 我做错了什么,是临时工。清除或声明临时哈希映射的位置
HashMap<String, HashMap<String, String>> csvList = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> tempMap = new HashMap<String, String>();
List<String> line = null;
try {
inputStream = new FileInputStream(csvFile);
//scanner = new Scanner(inputStream);
scanner = new Scanner(inputStream, "UTF-8");
//scanner.useDelimiter("\r\n");
int i = 0;
while (scanner.hasNext()) {
//tempMap.clear();
if (i == 0) {
headList = parseLine(scanner.nextLine());
i++;
} else {
line = parseLine(scanner.nextLine());
pKey = "";
for (int j = 0; j < line.size(); j++) {
if (!selectClause.toLowerCase().contains(headList.get(j).toLowerCase()))
continue;
else {
// Change for multiple PKeys
if (primaryKey.toLowerCase().contains(headList.get(j).toLowerCase())) {
pKey = pKey + line.get(j);
}
if (headList.get(j).equalsIgnoreCase(primaryKey))
pKey = line.get(j);
tempMap.put(headList.get(j).toLowerCase(), line.get(j));
}
}
//System.out.println(i++);
line.clear();
csvList.put(pKey, tempMap);
}
//tempMap.clear();
}
headList.clear();
//tempMap.clear();
scanner.close();
}
return csvList;
}
# 1 楼答案
在while循环外部创建tempMap,使其与您一直使用的实例相同,将创建移动到循环内部,使csvList中的每个pKey都获得一个唯一的实例