You could pass the list as a string directly into the CSVParser instead of creating a writer.
CSVRecord csvr = CSVParser.parse(
values.stream().collect(Collectors.joining(","))
,csvFormat.withHeader(header.toArray(new String[header.size()])))
.getRecords().get(0);
Answer from Berkley Lamb on Stack OverflowYou could pass the list as a string directly into the CSVParser instead of creating a writer.
CSVRecord csvr = CSVParser.parse(
values.stream().collect(Collectors.joining(","))
,csvFormat.withHeader(header.toArray(new String[header.size()])))
.getRecords().get(0);
The BeanIO and SimpleFlatMapper are way better at solving this problem. BeanIO uses a Map data structure and a config file to declare how the CSV file should be structured so it is very powerful. SimpleFlatMapper will take you POJO properties as the heading names by default and output the property values are column values.
BeanIO
http://beanio.org/2.1/docs/reference/index.html#CSVStreamFormat
SimpleFlatMapper
http://simpleflatmapper.org/
CsvParser
.mapTo(MyObject.class)
.stream(reader)
.forEach(System.out::println);
You can simply iterate over the resulting records and access the i-th item of a record via record.get(i), e.g.
Reader in = new StringReader(
"DAR_123451 ,\"XXXXX Hello World Hello World XXX \"\n" +
"DAR_123452 ,\"XXXXX Hello World Hello World XXX \"");
Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
for (CSVRecord record : records) {
for (int i = 0; i < record.size(); i++) {
System.out.println("At " + i + ": " + record.get(i));
}
}
You can access the column names (keys and values) of a CSVRecord by doing:
private void printRecords(final CSVParser csvRecords) {
for (CSVRecord csvRecord : csvRecords) {
for (Entry<String, String> column : csvRecord.toMap().entrySet()) {
System.out.println(column.getKey() + "=" + column.getValue());
}
}
}
Alternatively you can iterate over CSVRecord in the same way like over java.util.ArrayList.