We need to tell the parser to process the header line for us. We specify that as part of the CSVFormat, so we'll create a custom format like this:

CSVFormat csvFormat = CSVFormat.RFC4180.withFirstRecordAsHeader();

Question code used DEFAULT, but this is based on RFC4180 instead. Comparing them side-by-side:

DEFAULT                               RFC4180                       Comment
===================================   ===========================   ========================
withDelimiter(',')                    withDelimiter(',')            Same
withQuote('"')                        withQuote('"')                Same
withRecordSeparator("\r\n")           withRecordSeparator("\r\n")   Same
withIgnoreEmptyLines(true)            withIgnoreEmptyLines(false)   Don't ignore blank lines
withAllowDuplicateHeaderNames(true)   -                             Don't allow duplicates
===================================   ===========================   ========================
                                      withFirstRecordAsHeader()     We need this

With that change, we can call get(String name) instead of get(int i):

User currentUser = new User(
        Integer.parseInt(csvRecord.get("id")),
        csvRecord.get("first"),
        csvRecord.get("last"),
        csvRecord.get("city")
);

Note that CSVParser implements Iterable<CSVRecord>, so we can use a for-each loop, which makes the code look like this:

String path = "./data/data.csv";

Map<Integer, User> map = new HashMap<>();
try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(Paths.get(path)),
                                         CSVFormat.RFC4180.withFirstRecordAsHeader())) {
    for (CSVRecord csvRecord : csvParser) {
        User currentUser = new User(
                Integer.parseInt(csvRecord.get("id")),
                csvRecord.get("first"),
                csvRecord.get("last"),
                csvRecord.get("city")
        );
        map.put(currentUser.getId(), currentUser);
    }
}

That code correctly parses the file, even if the column order changes, e.g. to:

last,first,id,city
doe,john,1,austin
mary,jane,2,seattle
Answer from Andreas on Stack Overflow
🌐
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVParser.html
CSVParser (Apache Commons CSV 1.14.2-SNAPSHOT API)
For those who like fluent APIs, parsers can be created using CSVFormat.parse(java.io.Reader) as a shortcut: for (CSVRecord record : CSVFormat.EXCEL.parse(in)) { ... } To parse a CSV input from a file, you write: File csvData = new File("/path/to/csv"); CSVParser parser = CSVParser.parse(csvData, ...
Top answer
1 of 1
4

We need to tell the parser to process the header line for us. We specify that as part of the CSVFormat, so we'll create a custom format like this:

CSVFormat csvFormat = CSVFormat.RFC4180.withFirstRecordAsHeader();

Question code used DEFAULT, but this is based on RFC4180 instead. Comparing them side-by-side:

DEFAULT                               RFC4180                       Comment
===================================   ===========================   ========================
withDelimiter(',')                    withDelimiter(',')            Same
withQuote('"')                        withQuote('"')                Same
withRecordSeparator("\r\n")           withRecordSeparator("\r\n")   Same
withIgnoreEmptyLines(true)            withIgnoreEmptyLines(false)   Don't ignore blank lines
withAllowDuplicateHeaderNames(true)   -                             Don't allow duplicates
===================================   ===========================   ========================
                                      withFirstRecordAsHeader()     We need this

With that change, we can call get(String name) instead of get(int i):

User currentUser = new User(
        Integer.parseInt(csvRecord.get("id")),
        csvRecord.get("first"),
        csvRecord.get("last"),
        csvRecord.get("city")
);

Note that CSVParser implements Iterable<CSVRecord>, so we can use a for-each loop, which makes the code look like this:

String path = "./data/data.csv";

Map<Integer, User> map = new HashMap<>();
try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(Paths.get(path)),
                                         CSVFormat.RFC4180.withFirstRecordAsHeader())) {
    for (CSVRecord csvRecord : csvParser) {
        User currentUser = new User(
                Integer.parseInt(csvRecord.get("id")),
                csvRecord.get("first"),
                csvRecord.get("last"),
                csvRecord.get("city")
        );
        map.put(currentUser.getId(), currentUser);
    }
}

That code correctly parses the file, even if the column order changes, e.g. to:

last,first,id,city
doe,john,1,austin
mary,jane,2,seattle
🌐
Medium
medium.com › @zakariafarih142 › mastering-csv-parsing-in-java-comprehensive-methods-and-best-practices-a3b8d0514edf
Mastering CSV Parsing in Java: Comprehensive Methods and Best Practices | by Zakariafarih | Medium
November 25, 2024 - package org.example; import java.io.File; import java.io.IOException; import java.util.Scanner; public class CSVParserScanner { /* Pros: Simple to implement. Cons: Similar limitations as the split approach.
🌐
Oracle
docs.oracle.com › middleware › 12213 › adf › api-reference-model › oracle › adf › model › adapter › dataformat › csv › CSVParser.html
CSVParser (Oracle Fusion Middleware Java API Reference for Oracle ADF Model)
java.lang.Object · oracle.adf.model.adapter.dataformat.csv.CSVParser · public final class CSVParser extends java.lang.Object · Excel CSV Parser. If no encoding is passed to the constructor, the default encoding used to read the CSV file is "UTF8". Rules of Excel CSV ·
Find elsewhere
🌐
SourceForge
opencsv.sourceforge.net › apidocs › com › opencsv › CSVParser.html
CSVParser (opencsv 5.12.0 API)
The purpose of the CSVParser is to take a single string and parse it into its elements based on the delimiter, quote and escape characters.
🌐
Reddit
reddit.com › r/programming › benchmarking every (working) csv parser for java in existence.
r/programming on Reddit: Benchmarking every (working) CSV parser for Java in existence.
October 5, 2014 - the CsvParser is a push parser, you give it an class that implements CharsCellHandler and it will give you a call back per cell. Though the content is not unescaped. The CsvMapper will do the unescaping and creation of String or long.
🌐
Apache Commons
commons.apache.org › proper › commons-csv › jacoco › org.apache.commons.csv › CSVParser.java.html
CSVParser.java
* </p> * * <p> * To parse CSV input in a format like Excel, you write: * </p> * * <pre> * CSVParser parser = CSVParser.parse(csvData, CSVFormat.EXCEL); * for (CSVRecord csvRecord : parser) { * ... * } * </pre> * * <p> * If the predefined formats don't match the format at hand, custom formats can be defined. More information about * customizing CSVFormats is available in {@link CSVFormat CSVFormat Javadoc}. * </p> * * <h2>Parsing into memory</h2> * <p> * If parsing record-wise is not desired, the contents of the input can be read completely into memory.
🌐
FastCSV
fastcsv.org
Welcome to FastCSV | FastCSV
FastCSV is a high-performance CSV parser and writer for Java licensed under the MIT open source license.
🌐
IBM
ibm.com › docs › en › imdm › 11.6.0
CSVParser Java sample
March 14, 2024 - This sample parser parses a reader stream and tokenizes the stream based on a comma (`,`). The stream is broken down into lines, which are then tokenized. An empty string token is returned if the parser finds two consecutive commas (`,`) or if the line starts or ends with a comma.
🌐
Javadoc.io
javadoc.io › static › org.apache.commons › commons-csv › 1.6 › index.html
CSVParser (Apache Commons CSV 1.6 API)
JavaScript is disabled on your browser · Frame Alert · This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to Non-frame version
🌐
MojoAuth
mojoauth.com › parse-and-generate-formats › parse-and-generate-csv-with-java
Parse and Generate CSV with Java | Parse and Generate Formats
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; public class CsvReaderExample { public static void main(String[] args) throws IOException { try (Reader reader = new FileReader("data.csv"); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader())) { for (CSVRecord record : csvParser) { String name = record.get("Name"); String age = record.get("Age"); System.out.println("Name: " + name + ", Age: " + age); } } } }
🌐
CodersLegacy
coderslegacy.com › home › learn java › java csv parser – apache commons
Java CSV Parser - Apache Commons - CodersLegacy
October 6, 2022 - import org.apache.commons.csv.*; import java.io.*; public class example { public static void main(String[] args) throws IOException { CSVParser parser; FileReader Data = new FileReader("Data.txt"); parser = CSVParser.parse(Data, CSVFormat.DEFAULT.withFirstRecordAsHeader()); for (CSVRecord csvRecord : parser) { System.out.println(csvRecord.get("Name")); System.out.println(csvRecord.get("Age")); System.out.println(csvRecord.get("Gender")); } //System.out.println(parser.getRecords()); } }
🌐
Blogger
javarevisited.blogspot.com › 2015 › 06 › 2-ways-to-parse-csv-files-in-java-example.html
2 Ways to Parse CSV Files in Java - BufferedReader vs Apache Commons CSV Example
August 7, 2021 - This contains several CSVRecord ... /** * Java Program to parse and read CSV file using traditional BufferedReader * approach and by using more functional CSV parser from Apache Commons CSV * library....
Top answer
1 of 4
9

Side-effects

Stream.forEach() operation should be utilized with care since it operates via side-effects and should not be used as a substitution of a proper reduction operation.

The way you've written this stream is discouraged by the Stream API documentation because it makes code more cluttered and difficult to follow and more importantly your solution is broken with parallel streams (there should be no assumptions on the nature of the stream in your code).

In this particular case, you should be using Stream.toArray() operation instead.

Multiline lambdas

Try to void them. They bear a lot of cognitive load. If a lambda expression requires several lines or when you have a complex single-line lambda (e.g. with a nested stream in it), consider introducing a method.

Exceptions

In short, the purpose of exceptions is to indicate cases when it's not possible to proceed with the normal execution flow.

If you stumbled on a corrupt piece of data which violates invariant that are important for your business logic, usually you don't want to proceed processing it. That's a valid case to throw. You asked can you "throw from a stream"? Sure, it's just a means iteration.

I've seen some bickering over whether it's appropriate to use exceptions for the purpose of validation. Sure it is, we do employ Exceptions for Validation for decades.

Unless you're using exceptions to avoid conditional logic, or to make weird hacks like throwing in order to break from a recursive method, and you have a genuine invalid piece of data on your hands you can and should throw.

Another, important note: exceptions should be informative. If standard exception types can describe the case at hand, fine, if not introduce your own exception type.

Also, use proper exception messages that will be helpful in investigating the issue.

Static routines

Don't treat everything as util classes, use the Power of object-orientation to make more clean, cohesive and testable.

Refactored version

public class ArrayParser {
    private final String separator;
    private final int columnCount;
    
    public ArrayParser(String separator, int columnCount) {
        this.separator = separator;
        this.columnCount = columnCount;
    }
    
    public String[][] parse(final String str) {
        return str.lines()
            .map(this::parseLine)
            .toArray(String[][]::new);
    }
    
    private String[] parseLine(String toParse) {
        String[] line = toParse.split(separator);
        validateLine(line);
        return line;
    }
    
    private void validateLine(String[] line) {
        if (line.length != columnCount) {
            throw new LineParsingException(line, columnCount);
        }
    }
}

Exception example:

private class LineParsingException extends RuntimeException {
    private static final String MESSAGE_TEMPLATE = """
            The actual number of columns in the line
            %s
            doesn't match the expected number of columns %d""";
    
    public LineParsingException(String[] line, int columnsExpected) {
        super(MESSAGE_TEMPLATE.formatted(Arrays.toString(line), columnsExpected));
    }
}
2 of 4
7

conservative design

Since this is billed as "a CSV parser", a caller may reasonably believe they could send it any *.csv file produced by Excel. Better to advertise it as MyRestrictedCsvParser. The /** javadoc */ comments should explain the restrictions.

  1. Each field may or may not be enclosed in double quotes

This library should probably throw a fatal error upon encountering an ASCII 34 " double quote anywhere in an input line. Then a caller would not accidentally consume a data file in the belief that it had been parsed one way when in fact the library parsed it another way. That is, part of scoping down requirements is reducing the space of inputs you're willing to claim you successfully processed.

informative diagnostic

Throwing an unchecked exception within the JVM is great. It makes your library easier for callers to consume.

                throw new RuntimeException();

This is not a very diagnostic error. It needs two improvements:

  1. Subclass RuntimeException to create a library-specific error, perhaps CsvParseException.
  2. Mention the values of split.length and cols in the message, to save a maintenance engineer a little effort in diagnosing and repairing buggy inputs.

Consider keeping track of which line number we're on, so that can be included in the diagnostic message.

A caller should not be forced to catch a generic RuntimeException to recover from an error it knows how to deal with. We define new app-specific exception types to permit fine-grained catching. Lumping "wrong column count", "found a quote", and "zero lines" together would be acceptable, at least until you see how callers actually behave. If it turns out that callers really do wish to distinguish between those errors, then a v2 library release could always offer finer granularity on the error types.

signature

Clearly the OP code works. It seems slightly less convenient for the caller than it might be. There is redundant information encoded in the str and cols parameters.

Consider setting cols based on number of fields found in the first line of input.

🌐
Tarql
tarql.github.io › javadocs › org › deri › tarql › CSVParser.html
CSVParser
com.hp.hpl.jena.util.iterator....il.iterator.ClosableIterator<com.hp.hpl.jena.sparql.engine.binding.Binding> Parses a CSV file presented as a Reader, and delivers results as an iterator of Bindings....
🌐
Apache Commons
commons.apache.org › proper › commons-csv › user-guide.html
User Guide – Apache Commons CSV
The User Guide migrated to the Javadoc · Copyright © 2005-2025 The Apache Software Foundation. All Rights Reserved
🌐
Coderanch
coderanch.com › t › 657218 › java › Apache-Commons-CSV-Parser
Question on Apache Commons CSV Parser (Java in General forum at Coderanch)
October 28, 2015 - My code has TWO for-each loops which should both iterate through the CSVRecord(s) contained within the CSV Parser object. I don't know why ??.