How to Convert List<String[]> to Comma Separated String without " " in Java

836 Views Asked by At

I'm trying to remove fist line from the CSV file after reading it. Code is working properly but it's adding "" to my data when it's rewriting. for an example:

  • before write to csv file: 100,COMRADE,CAMPBELL
  • after write to csv file: "100","COMRADE","CAMPBELL"

    Here is the code.

========================================================================

public void deleteLineFromCsv() throws IOException {
        List<PatientsTabData> list = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new FileReader(new File("src/main/resources/patients.csv")));
        String line = reader.readLine();
        while(line != null) {
            String[] split = line.split(",");
            list.add(new PatientsTabData().patientId(Integer.parseInt(split[0])).patName(split[1]).patLastName(split[2]));
            line = reader.readLine();
        }
        list.remove(0);
        CSVWriter writer = new CSVWriter(new FileWriter(new File("src/main/resources/patients.csv")));
        List<String[]> newlist = list.stream().map(item -> new String[]
                {String.valueOf(item.getPatientId()), item.getPatName(), item.getPatLastName()})
                .collect(Collectors.toList());
        writer.writeAll(newlist);
        writer.close();
    }

Library:

        <dependency>
            <groupId>net.sf.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>2.3</version>
        </dependency>
3

There are 3 best solutions below

0
On

You can use another constructor when creating your writer. Change

CSVWriter writer = new CSVWriter(new FileWriter(new File("src/main/resources/patients.csv")));

to

CSVWriter writer = new CSVWriter(new FileWriter(new File("src/main/resources/patients.csv")),',',CSVWriter.NO_QUOTE_CHARACTER);
5
On

this is the way to convert List to comma Seprated Single String.

List<String[]> oldList= . . . ;
String requiredString = oldList
.stream()
    .map(Arrays::asList)
    .flatMap(Collection::stream)
    .collect(Collectors.joining(","));
0
On

Your CSV writer is writing each element as string in the csv file. This can be by design in library as it will keep any comma in your data in the string and later will not add extra column if your data has comma as well.

"name","class","house, street, city","value"

See the documentation of your library and check if it provides the option to not treat every element as string.

But my opinion is to keep the strings in quotes to avoid data descripency during reads.