[英]Java Print array on the same line with separator
我有一个从文件中读取特定列并将其插入数组的类。 我想用逗号分隔符将该数组打印在同一行上。
下面是我的代码:
public static void getArray(int Column, File path, String Splitter) throws IOException
{
List<String> lines = Files.readAllLines(path.toPath(), StandardCharsets.US_ASCII);
for (String line : lines)
{
String[] array = line.split(Splitter);
//Will return all elemetns on the same line but without any separation, i need some kind of separation
// if i use System.out.print(array[Column]+" ,");
// i will always get a , at the end of the line
System.out.print(array[Column]);
}
}
getArray(3, file, "|");
当前输出为:
abcdefg
所需的输出是:
a,b,c,d,e,g
您可以使用joining
收集器。
加入与分隔符的阵列的元件,
。
String result = Arrays.stream(array)
.collect(Collectors.joining(","));
加入与分隔符的阵列内的给定元素的字符,
。
String result = Arrays.stream(array[Column].split(""))
.collect(Collectors.joining(","));
与分隔符阵列内加入一个给定元素的字符的另一个变型,
:
String result = array[Column].chars()
.mapToObj( i -> String.valueOf((char)i))
.collect(Collectors.joining(","));
您可以在不使用流的情况下做到这一点(在Java 8+中,对于String.join
):
String.join(",", array)
但是您也可以使用简单的旧循环来完成此操作:
String delim = "";
for (String part : array) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.