If I have a String[]
(assume no commas) I can produce a CSV row simply. 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};
? (I consider using Arrays.toString
and slicing off the ends to be ugly.)
This can be done with the Streams API in a one-liner:
Arrays.stream(new int[] {0, 1, 2}).mapToObj(String::valueOf).collect(joining(","));
(assuming import static java.util.stream.Collectors.joining
)
Consider using the new (Java 8) StringJoiner .
For a 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[] 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.