将数字数组转换为CSV字符串的最佳方法?

时间:2014-07-03 20:30:48

标签: java csv java-8

如果我有String[](假设没有逗号),我可以简单地生成CSV行。如,

String[] header = {"header0", "header1", "header2"};
String joined = String.join(",", header);

int[] vals01 = {0, 1, 2};说等同的好方法是什么? (我考虑使用Arrays.toString并将两端切成丑陋。)

2 个答案:

答案 0 :(得分:8)

这可以通过单行代码中的Streams API完成:

Arrays.stream(new int[] {0, 1, 2}).mapToObj(String::valueOf).collect(joining(","));

(假设import static java.util.stream.Collectors.joining

答案 1 :(得分:5)

考虑使用新的(Java 8)StringJoiner

对于String[]

String[] header = {"header0", "header1", "header2"};
StringJoiner joiner = new StringJoiner(",");
Arrays.stream(header).forEach(joiner::add);
String joined = joiner.toString();

对于int[]

的情况
int[] ints = {1, 2, 3};
StringJoiner joiner = new StringJoiner(",");
Arrays.stream(ints).forEach(i -> joiner.add(Integer.toString(i)));
String joined = joiner.toString();
System.out.println(joined);