Guava Table 到 CSVPrinter header

Guava Table to CSVPrinter with header

这个问题是 的延伸。 OP 要求在 CSVPrinter 的帮助下打印番石榴 Table:

final Table<String, String, Double> graph = HashBasedTable.create();

graph.put("A", "FirstCol", 0.0);
graph.put("A", "SecondCol", 1.0);
graph.put("B", "FirstCol", 0.1);
graph.put("B", "SecondCol", 1.1);

final Appendable out = new StringBuilder();
try {
    final CSVPrinter printer = CSVFormat.DEFAULT.print(out);

    printer.printRecords(graph.rowMap().entrySet()
      .stream()
      .map(entry -> ImmutableList.builder()
            .add(entry.getKey())
            .addAll(entry.getValue().values())
            .build())
      .collect(Collectors.toList()));

} catch (final IOException e) {
    e.printStackTrace();
}

System.out.println(out);

使用前面的代码集成了已接受的答案,CSVPrinter 打印以下内容 table:

A,0.0,1.0
B,0.1,1.1

我想知道是否有一种方法可以将 table 列键中的字符串存储为 CSV 的 header,因此在示例中它应该打印以下内容:

AorB,FirstCol,SecondCol
A,0.0,1.0
B,0.1,1.1

提前致谢!

Apache Commons CSV 用户指南的

部分 Printing with headers 建议使用 CSVFormat.withHeader。在您的情况下,它可能看起来像:

final String[] header = new ImmutableList.Builder<String>()
    .add("AorB").addAll(graph.columnKeySet())
    .build().toArray(new String[0]);
final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(header).print(out);