java - 如果一个键有多个值,如何将 csv 转换为 Hashmap? (不使用 csv 阅读器)

标签 java csv hashmap

这里是说明从 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/

相关文章:

java - Lucene 分析器用于简单的直接字段搜索

java - 如何在 java swing 表单之间发送信号?

java - 从命令行在 Maven 中设置 cucumber-jvm 选项

java - 将整数添加到 HashMap

java - HashMap 将消耗多少大小?

java - 写入已存在的文件 - 但我有一个问题

java - 将 CSV 文件解析为 HashMap 存储空值

scala - 列出文件 scala emr hdfs(缺少 csv 文件)

mysql - 在 MySQL 中快速将逗号分隔的字符串转换为列表

flutter - 如何从列表Flutter中的 map 中检索值?