【问题标题】:Inserting values in LinkedHashMap without using the key在 LinkedHashMap 中插入值而不使用键
【发布时间】:2016-06-23 07:26:18
【问题描述】:

我有一个 CSV 格式的表格数据。第一行包含所有列名(键),所有后续行都是记录(值),如下所示:

ID,Name,Contact,Address
1,Alex,987654321,CA USA
2,Bob,4489398,LA USA
3,Marley,7236487,Washington

我正在阅读此文件并尝试将记录作为键值对存储在 LinkedHashMap 中。这是我的代码来显示我正在尝试做的事情。我的问题作为注释写在代码中。

public static void readCSV() throws IOException {

    BufferedReader br = new BufferedReader(new FileReader("table.csv"));

    Map<String, ArrayList<String>> map = new LinkedHashMap<>();

    String line = br.readLine();
    String[] keys = line.split(",");

    /*insert all keys with a corresponding empty arraylist as value to store
    all values of a particular key. ie each arralist will contain all values
    of individual columns. Since it is a linkedhashmap, keys are stored in 
    same order as they appear in the csv file*/

    for (String key : keys) {
        map.put(key, new ArrayList<String>());
    }

    while((line = br.readLine())!=null){
        String[] values = line.split(",");

        for (String value : values) {

            /*here I want to get the arraylists sequentially to store value.
            I know the first value goes in the first arraylist, second goes
            to second arraylist and so on.

            Is there a way to do this without using the key here??
            */

        }
    }
}

【问题讨论】:

  • 为什么这个数据结构而不是映射键 -> columnIndex 和 String[] 列表(每行一个)?
  • 最好将每一行解析为自定义对象并将它们放入列表中。

标签: java file dictionary collections linkedhashmap


【解决方案1】:

您可以使用Iterator 来迭代您的Map 的值:

while((line = br.readLine())!=null){
    String[] values = line.split(",");

    Iterator<ArrayList<String>> iter = map.values().iterator ();
    for (String value : values) {

        if (iter.hasNext()) {
            iter.next().add(value);
        }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2020-07-22
    相关资源
    最近更新 更多