LucasSeveryn LucasSeveryn - 4 months ago 69
Java Question

Guava table to CSV

I am attempting to export a Guava table to CSV. The code below works, but it skips the first column which I want to see in the output as well. Can you suggest anything?

EDIT: obviously using

values()
and
keySet()
separately works.

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


EDIT: this doesn't work either:

printer.printRecords(//
graph.rowMap().entrySet().stream().map(entry -> {
List a = Arrays.asList(entry.getKey());
a.addAll(entry.getValue().values());
return a;
}).collect(Collectors.toList())
);

Answer

You'll want to use entrySet() instead of values() and then map each entry to a list of its key and values:

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