使用 Apache Commons CSV 从 Header 的 HashMap 列表中写入 CSV

Write CSV from List of HashMaps with Header using Apache Commons CSV

我必须使用 HashMapArrayList 并使用 Apache Commons CSV 创建一个 CSV。但是,它没有将值写入右侧 headers。有没有一种简单的方法可以让库使用枚举自动将值放在右边 headers ?我不想手动分配它,因为我将添加更多列。

这是它正在生成的内容:

这是我的:

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);
}

好的,明白了。我将地图更改为 LinkedHashMap 以保留顺序然后这样做:

   try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile));
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
        .withHeader(Header.class));)
   {

        for (Map<Header, String> val : output)
        {
            csvPrinter.printRecord(val.values().toArray());
        }

        csvPrinter.flush();

    } catch (IOException ex)
    {
        Logger.getLogger(TestCSV.class.getName()).log(Level.SEVERE, null, ex);
    }