简体   繁体   中英

Convert List<List<String>> to csv

List<String> a=new ArrayList<>();
a.add("Ross");
a.add("Rachel")'
List<String> b=new ArrayList<>();
b.add("Chandler");
b.add("Monica")'
List<String> c=new ArrayList<>();
c.add("Joey");
c.add("Phoebe");
List<List<String>> x=new ArrayList<>();
x.add(a);
x.add(b);
x.add(c);

I want to convert the list of list of strings x to csv? How to achieve that?

The csv should look like-

Ross Rachel

Chandler Monica

Joey Phoebe

A simple csv writer could look like this:

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

Not that if any of your strings contain a comma, that field should be wrapped with double-quotes, eg "A,C" . The code above does not do that. Fields that contain newlines or double-quotes should also be escaped. There's no single specification that defines how these escapes work in all cases, so that sometimes turns into trial and error to see what works in the app your file will be imported into.

Sometimes csv files have comma separated field names in the first first line, sometimes not.

Variants of csv use different characters for field separator, eg "\t" or "|"

There are libraries such as opencsv that handle these complexities, so for non-trivial cases it can be useful to use those instead of re-inventing basic functionality like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM