[英]Guava Table to CSVPrinter with header
这个问题的扩展,这一个。 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);
使用前面集成了已接受答案的代码, CSVPrinter
打印下表:
A,0.0,1.0
B,0.1,1.1
我想知道是否有一种方法可以将表列键中的字符串存储为 CSV 的标题,因此在示例中它应该打印以下内容:
AorB,FirstCol,SecondCol
A,0.0,1.0
B,0.1,1.1
提前致谢!
使用Apache Commons CSV 用户指南的标题打印部分建议使用CSVFormat.withHeader 。 在您的情况下,它可能看起来像:
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.