如果我有String[]
(假设没有逗号),我可以简单地生成CSV行。如,
String[] header = {"header0", "header1", "header2"};
String joined = String.join(",", header);
用int[] vals01 = {0, 1, 2};
说等同的好方法是什么? (我考虑使用Arrays.toString
并将两端切成丑陋。)
答案 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);