番石榴 table 转 CSV

Guava table to CSV

我正在尝试将 Guava table 导出到 CSV。下面的代码有效,但它也跳过了我想在输出中看到的第一列。你有什么建议吗?

编辑:显然单独使用 values()keySet() 是可行的。

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

编辑:这也不起作用:

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

returns 只有 table 的值而不是键(第一列),这是您在 CSV 中看不到的方式。

您只映射到值,您正在跳过键(它们是第一列)。 您可能希望使用

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

查看文档以获取更多信息

https://google.github.io/guava/releases/17.0/api/docs/com/google/common/collect/RowSortedTable.html

http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html?is-external=true

如果您有更多的字段,您可以随时将 Tripple 与 Map 切换。这类似于 JSon,其中每个对象都被描述为一个映射,其中键是属性,值是值。

class Tripple {
        String value1;
        String value2;
        Double value3;
     Tripple(String value1, String value2, Double value3) {
        super();
        this.value1 = value1;
        this.value2 = value2;
        this.value3 = value3;
    }  

     Map<String,Map<String,Integer>> map;
RowSortedTable<String, String, Double> maprows;
List<Tripple> triples = maprows.rowMap().entrySet().stream()
                                                    .map(t->{final List<Tripple>  tripples = new ArrayList<>();
                                                             t.getValue().entrySet()
                                                                                    .forEach(p->{tripples.add(new Tripple(t.getKey(),p.getKey(),p.getValue()));});
                                                             return tripples;})
                                                    .flatMap(t->t.stream())
                                                    .collect(Collectors.toList());

您需要使用 entrySet() instead of values(),然后将每个条目映射到其键和值的列表:

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