I have a class that is reading a specific column from a file and inserting it in a an array. I would like to have that array printed on the same line with a comma separator.
Below is my code:
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, "|");
Current output is:
abcdefg
Desired output is:
a,b,c,d,e,g
You can use a joining
collector.
to join the elements of the array with the delimiter ,
.
String result = Arrays.stream(array)
.collect(Collectors.joining(","));
to join the characters of a given element within the array with the delimiter ,
.
String result = Arrays.stream(array[Column].split(""))
.collect(Collectors.joining(","));
another variant of joining the characters of a given element within the array with the delimiter ,
:
String result = array[Column].chars()
.mapToObj( i -> String.valueOf((char)i))
.collect(Collectors.joining(","));