2

Are there any library supports Guava tables to csv format? I generated

RowSortedTable<String, String, Double> graph

But the generating process takes some time(some query processing is needed), so I want to save this intermediate result and want to read and use it again.

SUNDONG
  • 2,501
  • 5
  • 21
  • 37

2 Answers2

4

You can use Apache Commons CSV:

final RowSortedTable<String, String, Double> graph = TreeBasedTable.create();

graph.put("A", "0", 0.0);
graph.put("A", "1", 1.0);
graph.put("B", "0", 0.1);
graph.put("B", "1", 1.1);

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

    printer.printRecords(//
            graph.rowMap().values()//
                    .stream()//
                    .map(x -> x.values())//
                    .collect(Collectors.toList()));

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

System.out.println(out);
// 0.0,1.0
// 0.1,1.1
user987541
  • 56
  • 3
-3

To create a CSV file using Guava you can use Joiner.

  Joiner.on(",").join(yourStrings)

Try to drop the output of this utility into a file whith extension CSV.

  • 1
    `Joiner.join` expects an `Iterable`, which I believe a Guava `Table` is not. You would need to retrieve a _view_ to the table cells and pass that to `join`. In any case, all of the elements would be output on the same row. – Mick Mnemonic Sep 23 '15 at 12:34
  • 3
    CSVs aren't quite this trivial. You need to handle escaping. – djechlin Jun 29 '16 at 20:47