1

I have List<String> which I'm writing to a csv file but each row is written on one cell. How can I split them through "," ? I tried to set the delimiter but still it isn't working.
Code

Writer writer = new FileWriter("D://new.csv", true);
            CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
            csvPrinter.printRecords(myList);
2
  • Can you share a sample data of your myList ? Commented Jun 17, 2021 at 17:21
  • 2
    And share how you built the myList ? there might be better solutions Commented Jun 17, 2021 at 17:23

1 Answer 1

2

As the documentation states, when you give a List<String> it'll use it a one record, ie one row, ie each String in a cell.

If the given collection only contains simple objects, this method will print a single record like printRecord(Iterable)


You need a code that use the fact that each String is in fact a row, like

  • passing each String splitted a separate record

    List<String> myList = new ArrayList<>();
    for (String row : myList)
        csvPrinter.printRecord(row.split(","));
    
  • Split all String then pass the whole list as a list of records

    List<String> myList = new ArrayList<>();
    List<String[]> myListSplitted = myList.stream().map(row -> row.split(",")).collect(Collectors.toList());
    csvPrinter.printRecords(myListSplitted);
    
Sign up to request clarification or add additional context in comments.

4 Comments

There had better not be any commas in each String.
@WJS He talked about commas, that's why i used them
True, but sometimes, OP's don't realize that split isn't that smart.
That worked but I'm getting a warning. Type String[] of the last argument to method printRecord(Object...) doesn't exactly match the vararg parameter type. Cast to Object[] to confirm the non-varargs invocation, or pass individual arguments of type Object for a varargs invocation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.