我希望有人可以帮助解决以下问题:我有一个
的数组列表List<Transaction> transactions;
带字段:
private String firmId;
private String accountId;
private String symbol;
private long quantity;
我想转换为以下 CSV 格式的字符串:
firmId,AccountId,symbol, quantity
1234,ACCOUNT1,AAPL,100
1234,ACCOUNT1,AMZN,200
2345,ACCOUNT3,AAPL,400
Java 有没有一种高效且简单的方法来做到这一点?因为我不想使用 OpenCSV 并将其写入文件。我也不喜欢使用抽象的选项。
我需要在程序中使用 CSVString 作为另一个请求的有效负载。列表中的对象数量最多可达 2000 个。
谢谢!
为了获得您问题中发布的所需字符串,我建议如下:
toString
中的方法 Transaction
,以便它返回 Transaction
实例的所有属性值的串联,以逗号分隔。StringBuilder
并附加所需的标题,即 firmId,AccountId,symbol, quantity
。Transaction
实例列表,在每个实例上调用 toString
方法并将结果附加到 StringBuilder
。瞧,您已经得到了想要的结果。
下面的代码还处理空值属性并在必要时添加换行符,即
\n
。
import java.util.List;
public class Transaction {
private String firmId;
private String accountId;
private String symbol;
private long quantity;
public Transaction(String firmId, String accountId, String symbol, long quantity) {
this.firmId = firmId;
this.accountId = accountId;
this.symbol = symbol;
this.quantity = quantity;
}
@Override
public String toString() {
String firm = firmId == null ? "" : firmId;
String acct = accountId == null ? "" : accountId;
String smbl = symbol == null ? "" : symbol;
return firm + "," + acct + "," + smbl + "," + quantity;
}
public static void main(String[] args) {
List<Transaction> list = List.of(new Transaction("1234","ACCOUNT1","AAPL",100),
new Transaction("1234","ACCOUNT1","AMZN",200),
new Transaction("2345","ACCOUNT3","AAPL",400));
StringBuilder sb = new StringBuilder("firmId,AccountId,symbol, quantity\n");
list.forEach(t -> sb.append(t + "\n"));
System.out.println(sb);
}
}
运行上面代码时的输出:
firmId,AccountId,symbol, quantity
1234,ACCOUNT1,AAPL,100
1234,ACCOUNT1,AMZN,200
2345,ACCOUNT3,AAPL,400