作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这里是说明从 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 时,我得到的是: Fruit - [Grapefruit] Vegetable- [Celery]如何迭代循环并存储所有值?
以下是我编写的代码:
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);
}
}
}
最佳答案
目前,您正在为找到的每个值在 map 中放置一个新的ArrayList
。这将替换您为该特定 key 拥有的旧列表。相反,您应该使用现有的数组列表(如果它已经存在),并向其中添加您的值。
因此您应该替换它:
ArrayList<String> arrVal = new ArrayList<String>();
arrVal.add(token_rhs);
mp.put(token_lhs,arrVal);
通过这个:
ArrayList<String> arrVal = mp.get(token_lhs);
if (arrVal == null) {
arrVal = new ArrayList<String>();
mp.put(token_lhs,arrVal);
}
arrVal.add(token_rhs);
关于java - 如果一个键有多个值,如何将 csv 转换为 Hashmap? (不使用 csv 阅读器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22605414/
我是一名优秀的程序员,十分优秀!