Transforming a List<List<String>> into a csv format



This is an example of a basic csv writer.

Writer out = System.out; // this could be a FileWriter, StringWriter, etc.
for (List line : x) {
    int n = 0;
    for (String field : line) {
        if (n++ > 0) {
            out.write(",");  // field separator
    out.write("n"); // record separator

In case any of your strings contain a comma, it is necessary to enclose that field with double-quotes. For example, the


mentioned earlier does not implement this. Additionally, fields that include newlines or double-quotes need to be escaped. Since there is no universal specification governing these escapes, it often becomes a process of trial and error to determine what will work when importing your file into a specific application.

Occasionally, csv files may contain field names separated by commas in the initial line, while other times they may not.

Different characters, such as “t” or “|”, are used as field separators in various csv variants.

For cases that are not simple, it can be beneficial to utilize libraries like opencsv which manage these intricacies, rather than creating basic functionality from scratch.

Frequently Asked Questions