使用Apache Commons CSV从带有标题的HashMap列表中写入CSV [英] Write CSV from List of HashMaps with Header using Apache Commons CSV

查看:399
本文介绍了使用Apache Commons CSV从带有标题的HashMap列表中写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须采用HashMapArrayList并使用Apache Commons CSV创建CSV.但是,它没有将值写入正确的标题.有没有一种简单的方法可以使该库使用枚举将值自动放置到正确的标题中?我不想手动分配它,因为我将添加更多列.

I have to take an ArrayList of HashMap and create a CSV using Apache Commons CSV. However, it's not writing the values to the right headers. Is there an easy way to have the library automatically place the values to the right headers using the Enum? I don't want to manually assign it as I will be adding more columns.

这就是它所产生的:

这就是我所拥有的:

Header.java

Header.java

public enum Header
{
    FIRST_NAME(),
    LAST_NAME(),
    GENDER();
}

主要

public static void main(String[] args)
{
    List<Map<Header, String>> output = new ArrayList<>();

    Map<Header, String> map = new HashMap<>();
    map.put(Header.FIRST_NAME, "John");
    map.put(Header.LAST_NAME, "Andrew");
    map.put(Header.GENDER, "Male");
    output.add(map);

    Map<Header, String> map2 = new HashMap<>();
    map2.put(Header.FIRST_NAME, "Sally");
    map2.put(Header.LAST_NAME, "Andrew");
    map2.put(Header.GENDER, "Female");
    output.add(map2);

    String outputFile = System.getProperty("java.io.tmpdir")+"test.csv";

    try (
            BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile));
            CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
                    .withHeader(Header.class));)
    {
        csvPrinter.printRecords(output);
        csvPrinter.flush();
    } catch (IOException ex)
    {
        Logger.getLogger(TestCSV.class.getName()).log(Level.SEVERE, null, ex);
    }

}

推荐答案

这是怎么回事:

try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile));
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(Header.class));) {
    for (Map<Header, String> row : output) {
        csvPrinter.printRecord(Arrays.asList(Header.values())
                                     .stream()
                                     .map(header -> row.get(header))
                                     .collect(Collectors.toList()));
    }
} catch (IOException ex) {
    Logger.getLogger(TestCSV.class.getName())
          .log(Level.SEVERE, null, ex);
}

这篇关于使用Apache Commons CSV从带有标题的HashMap列表中写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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