[英]Best way to convert numeric array to CSV string?
If I have a String[]
(assume no commas) I can produce a CSV row simply. 如果我有一个
String[]
(假设没有逗号),我可以简单地生成一个CSV行。 Eg, 例如,
String[] header = {"header0", "header1", "header2"};
String joined = String.join(",", header);
What's the nice way to do the equivalent with say int[] vals01 = {0, 1, 2};
用
int[] vals01 = {0, 1, 2};
做等效的好方法是什么int[] vals01 = {0, 1, 2};
? ? (I consider using
Arrays.toString
and slicing off the ends to be ugly.) (我考虑使用
Arrays.toString
并切掉两端是丑陋的。)
This can be done with the Streams API in a one-liner: 这可以通过单行中的Streams API完成:
Arrays.stream(new int[] {0, 1, 2}).mapToObj(String::valueOf).collect(joining(","));
(assuming import static java.util.stream.Collectors.joining
) (假设
import static java.util.stream.Collectors.joining
)
Consider using the new (Java 8) StringJoiner . 考虑使用新的(Java 8) StringJoiner 。
For a String[]
: 对于
String[]
:
String[] header = {"header0", "header1", "header2"};
StringJoiner joiner = new StringJoiner(",");
Arrays.stream(header).forEach(joiner::add);
String joined = joiner.toString();
For the case of int[]
: 对于
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.