How to write ArrayList <Object> to csv file

I have an ArrayList<Metadata> , and I want to know if there is a Java API for working with CSV files that has a recording method that accepts an ArrayList <> as parameter similar to LinqToCsv in .Net. Since I know that OpenCSV is available, but the CsvWriter class does not accept the collection. My metadata class

 public class Metadata{ private String page; private String document; private String loan; private String type; } 
 ArrayList<Metadata> record = new ArrayList<Metadata>(); 

As soon as I write the record, I want to write each line to the csv file. Please suggest.

+7
java arraylist csv opencsv
source share
3 answers

Of course, there will be a bunch of APIs that do this for you, but why not do it yourself for such a simple case? This will save you addiction, which is good for any project of any size.

Create a toCsvRow() method in Metadata that toCsvRow() comma separated strings.

 public String toCsvRow() { return Stream.of(page, document, loan, type) .map(value -> value.replaceAll("\"", "\"\"")) .map(value -> Stream.of("\"", ",").anyMatch(value::contains) ? "\"" + value + "\"" : value) .collect(Collectors.joining(",")); } 

Collect the result of this method for each Metadata object, separated by a new line.

 String recordAsCsv = record.stream() .map(Metadata::toCsvRow) .collect(Collectors.joining(System.getProperty("line.separator"))); 

EDIT If you're out of luck with the Java 8 and Stream API at your disposal, it will be almost as easy using the traditional list.

 public String toCsvRow() { String csvRow = ""; for (String value : Arrays.asList(page, document, loan, type)) { String processed = value; if (value.contains("\"") || value.contains(",")) { processed = "\"" + value.replaceAll("\"", "\"\"") + "\""; } csvRow += "," + processed; } return csvRow.substring(1); } 
+8
source share

Using CSVWriter , you can convert an ArrayList to an array and pass it to the writer.

 csvWriter.writeNext(record.toArray(new String[record.size()])); 
+1
source share

If you have an ArrayList of Objects (Metadata in your case), you should use BeanToCSV instead of CSVWriter.

You can look at BeanToCSVTest in opencsv source code for examples of how to use it.

0
source share

All Articles