【发布时间】:2014-03-24 09:27:37
【问题描述】:
这里是从 csv 读取数据到 Hashmap 的链接。 Convert CSV values to a HashMap key value pairs in JAVA 但是,我正在尝试读取一个 csv 文件,其中给定键有多个值。 例如:
Key - Value
Fruit - Apple
Fruit -Strawberry
Fruit -Grapefruit
Vegetable -Potatoe
Vegetable -Celery
哪里,水果和蔬菜是关键。
我正在使用 ArrayList 来存储值。 我正在编写的代码能够存储键,但只存储最后一个对应的值。 所以,当我打印 hashmap 时,我得到的是:水果 - [葡萄柚] 蔬菜 - [芹菜] 如何遍历循环并存储所有值?
以下是我写的代码:
public class CsvValueReader {
public static void main(String[] args) throws IOException {
Map<String, ArrayList<String>> mp=null;
try {
String csvFile = "test.csv";
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line = "";
StringTokenizer st = null;
mp= new HashMap<String, ArrayList<String>>();
int lineNumber = 0;
int tokenNumber = 0;
//read comma separated file line by line
while ((line = br.readLine()) != null) {
lineNumber++;
//use comma as token separator
st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
tokenNumber++;
String token_lhs=st.nextToken();
String token_rhs= st.nextToken();
ArrayList<String> arrVal = new ArrayList<String>();
arrVal.add(token_rhs);
mp.put(token_lhs,arrVal);
}
}
System.out.println("Final Hashmap is : "+mp);
} catch (Exception e) {
System.err.println("CSV file cannot be read : " + e);
}
}
}
【问题讨论】: