Search code examples
javacsvguava

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:

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:

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:

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

Thanks in advance!


Solution

  • Section Printing with headers of Apache Commons CSV User Guide suggests using 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);