Java - 基于列将 CSV 解析为 Hashmap 和 Arraylist [英] Java - parse CSV into Hashmap and Arraylist based on columns

查看:37
本文介绍了Java - 基于列将 CSV 解析为 Hashmap 和 Arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想就这项任务寻求帮助:例如,我有 CSV 文件:

I would like to ask for help with this task: I have CSV for example like this:

column1$column2$column3
123$xyz$321
456$zyx$654

我想用 Java 解析它,所以我会为每一列提供一个数组列表的 Hashmap.例如:

And I would like to parse it by Java, so I would have a Hashmap of Array lists for every column. For example:

["column1",[123,456]]
["column2",[xyz,zyx]]
["column3",[321,654]]

谢谢大家.

有人已经给我建议如何通过数组列表的数组列表来解决这个任务,但我想使用Hashmap,所以我可以获得列的索引.我该如何编辑此代码?

Someone already gave me advice how to solve this task by array lists of array lists, but I would like to use the Hashmap, so I could have the index of the column. How could I edit this code?

public static void main(String[] args) {
    ArrayList<ArrayList<String>> columns = new ArrayList<ArrayList<String>>();
    BufferedReader br = null;
    try {
        String sCurrentLine;
        br = new BufferedReader(new FileReader("testing.cvs"));

        while ((sCurrentLine = br.readLine()) != null) {
            String[] fields = sCurrentLine.split("\\$");
            for (int i = 0; i < fields.length; i++) {
                if (columns.size()<=i){
                    columns.add(new ArrayList<String>());
                }
                columns.get(i).add(fields[i]);
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

谢谢大家

推荐答案

使用 univocity-parsers' ColumnProcessor 可靠地为您执行此操作:

Use univocity-parsers' ColumnProcessor to do this for you reliably:

CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setLineSeparator("\n");
parserSettings.getFormat().setDelimiter('$');
parserSettings.setHeaderExtractionEnabled(true);

// To get the values of all columns, use a column processor
ColumnProcessor rowProcessor = new ColumnProcessor();
parserSettings.setRowProcessor(rowProcessor);

CsvParser parser = new CsvParser(parserSettings);

//This will kick in our column processor
parser.parse(new FileReader("testing.cvs"));

//Finally, we can get the column values:
Map<String, List<String>> columnValues = rowProcessor.getColumnValuesAsMapOfNames();

比手工操作更干净、更快、更容易.这将处理诸如具有不同列数的行并将 null 添加到列表中而不是向您抛出异常的情况.

Clean, faster and easiers than doing it by hand. This will handle situations such as rows with different number of columns and add null to the list instead of throwing exceptions at you.

披露:我是这个库的作者.它是开源且免费的(Apache V2.0 许可).

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

这篇关于Java - 基于列将 CSV 解析为 Hashmap 和 Arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆