簡體   English   中英

番石榴表到帶有標題的 CSVPrinter

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM