简体   繁体   English

番石榴表到带有标题的 CSVPrinter

[英]Guava Table to CSVPrinter with header

This question is an extension to this one .这个问题的扩展,这一个 The OP asked to print a Guava Table with help of a CSVPrinter : OP 要求在CSVPrinter帮助下打印番石榴表:

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

With the previous code which integrates the accepted answer, the CSVPrinter prints the following table:使用前面集成了已接受答案的代码, CSVPrinter打印下表:

A,0.0,1.0
B,0.1,1.1

I want to know if there is a method to store the strings in the table column keys as a header for the CSV, so in the example it should print the following:我想知道是否有一种方法可以将表列键中的字符串存储为 CSV 的标题,因此在示例中它应该打印以下内容:

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

Thanks in advance!提前致谢!

Section Printing with headers of Apache Commons CSV User Guide suggests using CSVFormat.withHeader . 使用Apache Commons CSV 用户指南的标题打印部分建议使用CSVFormat.withHeader In your case it could look like:在您的情况下,它可能看起来像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM