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 Overflow
🌐
Apache Commons
commons.apache.org › proper › commons-csv › jacoco › org.apache.commons.csv › CSVRecord.java.html
CSVRecord.java - Apache Commons
*/ package org.apache.commons.csv; import java.io.Serializable; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; /** * A CSV record parsed from a CSV file.
🌐
Java Tips
javatips.net › api › org.apache.commons.csv.csvrecord
Java Examples for org.apache.commons.csv.CSVRecord
public static Collection<Lead> importFile(File f) { try { Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(new FileReader(f)); Iterator<CSVRecord> lines = records.iterator(); if (!lines.hasNext()) return null; CSVRecord headerRow = lines.next(); List<Lead> leads = new ArrayList<>(); while (lines.hasNext()) { final Iterator<String> content = lines.next().iterator(); final Iterator<String> header = headerRow.iterator(); Lead lead = new Lead(null, "new lead"); StringBuilder desc = new StringBuilder(); // use capterra as default campaign since it doesn't reference // itself in the import file C
🌐
GitHub
github.com › apache › commons-csv › blob › master › src › main › java › org › apache › commons › csv › CSVRecord.java
commons-csv/src/main/java/org/apache/commons/csv/CSVRecord.java at master · apache/commons-csv
import java.io.Serializable; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; · /** * A CSV record parsed from a CSV file.
Author   apache
🌐
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVRecord.html
CSVRecord (Apache Commons CSV 1.14.2-SNAPSHOT API)
java.lang.Object · org.apache.commons.csv.CSVRecord · All Implemented Interfaces: Serializable, Iterable<String> public final class CSVRecord extends Object implements Serializable, Iterable<String> A CSV record parsed from a CSV file. Note: Support for Serializable is scheduled to be removed in version 2.0.
🌐
CalliCoder
callicoder.com › java-read-write-csv-file-apache-commons-csv
Read / Write CSV files in Java using Apache Commons CSV | CalliCoder
February 18, 2022 - import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths; public class CSVReaderWithHeaderAutoDetection { private static final String SAMPLE_CSV_FILE_PATH = "./users-with-header.csv"; public static void main(String[] args) throws IOException { try ( Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH)); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT .withFirstRecor
🌐
GitHub
github.com › kana-ph › csv-viewer › blob › master › src-commons-csv › org › apache › commons › csv › CSVRecord.java
csv-viewer/src-commons-csv/org/apache/commons/csv/CSVRecord.java at master · kana-ph/csv-viewer
import java.util.Map.Entry; · · /** · * A CSV record parsed from a CSV file. · * · * @version $Id: CSVRecord.java 1727809 2016-01-31 13:08:33Z sebb $ · */ · public final class CSVRecord implements Serializable, Iterable<String> { · · private static final String[] EMPTY_STRING_ARRAY = new String[0]; ·
Author   kana-ph
🌐
Java2s
java2s.com › example › java-api › org › apache › commons › csv › csvrecord › get-1-0.html
Example usage for org.apache.commons.csv CSVRecord get
From source file:bariopendatalab.ImportData.java · /** * @param args the command line arguments *//*from ww w . ja v a 2 s .c o m*/ public static void main(String[] args) { int i = 0; try { MongoClient client = new MongoClient("localhost", 27017); DBAccess dbaccess = new DBAccess(client); dbaccess.dropDB(); dbaccess.createDB(); FileReader reader = new FileReader(new File(args[0])); Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().withIgnoreEmptyLines().withDelimiter(',') .parse(reader); i = 2; for (CSVRecord record : records) { String type = record.get("Tipologia"); if (type == null
Find elsewhere
🌐
Javadoc.io
javadoc.io › doc › org.apache.commons › commons-csv › 1.7 › org › apache › commons › csv › CSVRecord.html
CSVRecord (Apache Commons CSV 1.7 API)
Bookmarks · Latest version of org.apache.commons:commons-csv · https://javadoc.io/doc/org.apache.commons/commons-csv · Current version 1.7 · https://javadoc.io/doc/org.apache.commons/commons-csv/1.7 · package-list path (used for javadoc generation -link option) · https://javadoc.io/d...
🌐
Javadoc.io
javadoc.io › doc › org.apache.commons › commons-csv › 1.6 › org › apache › commons › csv › CSVRecord.html
CSVRecord (Apache Commons CSV 1.6 API)
https://javadoc.io/doc/org.apache.commons/commons-csv · Current version 1.6 · https://javadoc.io/doc/org.apache.commons/commons-csv/1.6 · package-list path (used for javadoc generation -link option) https://javadoc.io/doc/org.apache.commons/commons-csv/1.6/package-list ·
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
DZone
dzone.com › coding › java › working with csv files in java using apache commons csv
Working With CSV Files in Java Using Apache Commons CSV
April 30, 2018 - import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; public class BasicCsvReader { public static void main(String[] args) throws IOException { BufferedReader reader = Files.newBufferedReader(Paths.get("student.csv")); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader("Student Name", "Fees").withIgnoreHeaderCase().withTrim()); for (CSVRecord csvRecord: csvParser) { // Accessing Values by Co
🌐
GitHub
github.com › apache › commons-csv › blob › master › src › test › java › org › apache › commons › csv › CSVRecordTest.java
commons-csv/src/test/java/org/apache/commons/csv/CSVRecordTest.java at master · apache/commons-csv
import java.util.concurrent.atomic.AtomicInteger; · import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; · class CSVRecordTest { · private enum EnumFixture { UNKNOWN_COLUMN ·
Author   apache
🌐
Java Tips
javatips.net › api › jbasics-master › src › main › java › org › jbasics › csv › CSVRecord.java
CSVRecord.java example
*/ package org.jbasics.csv; import ...ner.Indexed; import org.jbasics.utilities.DataUtilities; import java.io.IOException; import java.util.*; @ThreadSafe @ImmutableState public class CSVRecord implements Iterable<String>, Indexed<String> { public final static CSVRecord EMPTY_RECORD ...
🌐
GitHub
github.com › sujaybhowmick › csv-parser › blob › master › src › main › java › com › optimus › csv › parser › CSVRecord.java
csv-parser/src/main/java/com/optimus/csv/parser/CSVRecord.java at master · sujaybhowmick/csv-parser
import java.util.Map; · /** * Created with IntelliJ IDEA. * User: sujay · * Date: 1/12/14 · * Time: 10:10 AM · * To change this template use File | Settings | File Templates. */ public final class CSVRecord implements Serializable, Iterable<String> { private static final String[] EMPTY_STRING_ARRAY = new String[0]; ·
Author   sujaybhowmick
Top answer
1 of 1
7

tl;dr

Using a CSV utility such as Apache Commons CSV, each row of incoming data can be passed to a parsing method you write, with the resulting Employee object collected into a List.

Iterable < CSVRecord > iterable = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
employees =
        StreamSupport
                .stream( iterable.spliterator() , false )
                .map( ( CSVRecord csvRecord ) -> Employee.parse( csvRecord ) )
                .collect( Collectors.toList() )
;

That Employee.parse method converts data from the CSVRecord to make a Employee object.

UUID id = UUID.fromString( csvRecord.get( "id" ) ) ;
String name = csvRecord.get( "name" ) ;
return new Employee( id , name ) ;

Details

Yes, you can load a List from a CSV file.

First, grab a CSV parsing utility such as https://commons.apache.org/proper/commons-csv/. You have a variety of such tools to choose from within the Java ecosystem.

Then define a Employee class with a factory method that parses the CSV input. In the case of Apache Commons CSV, that would be a CSVRecord object.

The important parse method of the Employee class.

// Parsing from Apache Commons CSV record
static public Employee parse ( CSVRecord csvRecord )
{
    UUID id = UUID.fromString( Objects.requireNonNull( csvRecord.get( "id" ) ) );
    String name = Objects.requireNonNull( csvRecord.get( "name" ) );
    Employee employee = new Employee( id , name );
    Objects.requireNonNull( employee );
    return employee;
}

The entire Employee class source code.

package work.basil.example;

import org.apache.commons.csv.CSVRecord;

import java.util.Objects;
import java.util.UUID;

public class Employee
{
    // Member fields.
    private UUID id;
    private String name;

    // Constructor.
    public Employee ( UUID id , String name )
    {
        this.id = Objects.requireNonNull( id );
        this.name = Objects.requireNonNull( name );
        if ( this.name.isBlank() ) { throw new IllegalArgumentException(); }
    }

    // Parsing from Apache Commons CSV record
    static public Employee parse ( CSVRecord csvRecord )
    {
        UUID id = UUID.fromString( Objects.requireNonNull( csvRecord.get( "id" ) ) );
        String name = Objects.requireNonNull( csvRecord.get( "name" ) );
        Employee employee = new Employee( id , name );
        Objects.requireNonNull( employee );
        return employee;
    }

    // Object overrides.


    @Override
    public String toString ( )
    {
        return "Employee{ " +
                "id=" + id +
                " | name='" + name + '\'' +
                " }";
    }

    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;
        Employee employee = ( Employee ) o;
        return getId().equals( employee.getId() );
    }

    @Override
    public int hashCode ( )
    {
        return Objects.hash( getId() );
    }

    // Getters.
    public UUID getId ( ) { return this.id; }

    public String getName ( ) { return this.name; }
}

And here is a demo of using that factory method to produce a List of Employee records from a CSV file. The main method here first creates a file. Notice the first row is a header row, declaring the name of each column. We use that name in our parsing code.

id,name
ac4f0541-4f39-4b8a-a49b-5e88405da503,Alice
ca4a3950-e7a1-4521-993f-1d4c78ecda8c,Bob
67ef39f8-688f-4795-8b41-76d972cad888,Carol

Then we read that newly created file, with Apache Commons CSV parsing each row as a CSVRecord which we pass to the static method Employee.parse. we get back a Employee record.

In our case with Apache Commons CSV, we get an Iterable of CSVRecord objects. We convert that Iterable to a Stream using StreamSupport as discussed in the Question, Convert Iterable to Stream using Java 8 JDK.

The core of the demo code.

    List < Employee > employees = List.of(); // Default to empty non-modifiable list.

    Path path = Paths.get( "/Users/basilbourque/csv.txt" );
    try (
            Reader reader = Files.newBufferedReader( path , StandardCharsets.UTF_8 ) ;
    )
    {
        Iterable < CSVRecord > iterable = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
        employees =
                StreamSupport
                        .stream( iterable.spliterator() , false )
                        .map( ( CSVRecord csvRecord ) -> Employee.parse( csvRecord ) )
                        .collect( Collectors.toList() )
        ;
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }

Entire demo code.

package work.basil.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class EmployeeDemo
{

    public static void main ( String[] args )
    {
        EmployeeDemo app = new EmployeeDemo();
        app.write();
        app.read();
    }

    private void write ( )
    {
        Path path = Paths.get( "/Users/basilbourque/csv.txt" );
        try (
                Writer writer = Files.newBufferedWriter( path , StandardCharsets.UTF_8 ) ;
                CSVPrinter printer = new CSVPrinter( writer , CSVFormat.RFC4180 ) ;
        )
        {
            printer.printRecord( "id" , "name" );
            printer.printRecord( UUID.randomUUID() , "Alice" );
            printer.printRecord( UUID.randomUUID() , "Bob" );
            printer.printRecord( UUID.randomUUID() , "Carol" );
        }
        catch ( IOException ex )
        {
            ex.printStackTrace();
        }
    }

    private void read ( )
    {
        List < Employee > employees = List.of(); // Default to empty non-modifiable list.

        Path path = Paths.get( "/Users/basilbourque/csv.txt" );
        try (
                Reader reader = Files.newBufferedReader( path , StandardCharsets.UTF_8 ) ;
        )
        {
            Iterable < CSVRecord > iterable = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
            employees =
                    StreamSupport
                            .stream( iterable.spliterator() , false )
                            .map( ( CSVRecord csvRecord ) -> Employee.parse( csvRecord ) )
                            .collect( Collectors.toList() )
            ;
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }
        System.out.println( "employees = " + employees );
    }
}

When run.

employees = [Employee{ id=ac4f0541-4f39-4b8a-a49b-5e88405da503 | name='Alice' }, Employee{ id=ca4a3950-e7a1-4521-993f-1d4c78ecda8c | name='Bob' }, Employee{ id=67ef39f8-688f-4795-8b41-76d972cad888 | name='Carol' }]

🌐
Opencrx
opencrx.org › opencrx › 3.0 › java › org › opencrx › application › uses › org › apache › commons › csv › CSVRecord.html
CSVRecord (openCRX/Core API)
java.lang.Object · org.opencrx.application.uses.org.apache.commons.csv.CSVRecord · All Implemented Interfaces: Serializable, Iterable<String> public class CSVRecord extends Object implements Serializable, Iterable<String> A CSV record · Version: $Id: $ See Also: Serialized Form ·