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 OverflowApache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVParser.html
CSVParser (Apache Commons CSV 1.14.2-SNAPSHOT API)
Parses the CSV input according to the given format and returns the content as a list of CSVRecords. ... Gets the trailer comment, if any. ... Checks whether there is a header comment. ... Checks whether there is a trailer comment. ... Tests whether this parser is closed.
Apache Commons
commons.apache.org › proper › commons-csv › user-guide.html
User Guide – Apache Commons CSV
Apache Commons, Apache Commons CSV, Apache, the Apache logo, and the Apache Commons project logos are trademarks of The Apache Software Foundation.
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › index.html
Overview (Apache Commons CSV 1.14.2-SNAPSHOT API)
Using the BOMInputStream class from Apache Commons IO simplifies this task; for example: try (Reader reader = new InputStreamReader(BOMInputStream.builder() .setPath(path) .get(), "UTF-8"); CSVParser parser = CSVFormat.EXCEL.builder() .setHeader() .get() .parse(reader)) { for (CSVRecord record ...
GitHub
github.com › apache › commons-csv › blob › master › src › main › java › org › apache › commons › csv › CSVParser.java
commons-csv/src/main/java/org/apache/commons/csv/CSVParser.java at master · apache/commons-csv
public static CSVParser parse(final URL url, final Charset charset, final CSVFormat format) throws IOException { ... * Lexer offset when the parser does not start parsing at the beginning of the source.
Author apache
Stack Abuse
stackabuse.com › reading-and-writing-csvs-in-java-with-apache-commons-csv
Reading and Writing CSVs in Java with Apache Commons CSV
February 20, 2019 - The Apache Commons CSV library is the Apache Software Foundation's version of a Java CSV parser.
Apache Commons
commons.apache.org › proper › commons-csv › jacoco › org.apache.commons.csv › CSVParser.java.html
CSVParser.java - Apache Commons
*/ package org.apache.commons.csv; ...ild.AbstractStreamBuilder; import org.apache.commons.io.function.Uncheck; /** * Parses CSV files according to the specified format. * * Because CSV appears in many different dialects, the parser supports many formats by allowing the * specification ...
Maven Repository
mvnrepository.com › artifact › org.apache.commons › commons-csv
Maven Repository: org.apache.commons » commons-csv
July 27, 2025 - The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
Apache Commons
commons.apache.org › proper › commons-csv › apidocs › org › apache › commons › csv › CSVFormat.html
CSVFormat (Apache Commons CSV 1.14.2-SNAPSHOT API)
ignoreSurroundingSpaces - the parser trimming behavior, true to remove the surrounding spaces, false to leave the spaces as is. ... A new CSVFormat that is equal to this but with the specified trimming behavior.
Stack Overflow
stackoverflow.com › questions › 51744690 › apache-commons-csv-parser
java 8 - Apache commons CSV parser - Stack Overflow
public List<Map<String, Object>> getMapFromCSV(MultipartFile multipartFile) { try { CSVParser parser = parseCSV(multipartFile.getInputStream()); return getMap(parser.getRecords(), parser.getHeaderMap()); } catch (IOException e) { throw new RunTimeException(e); } } private List<Map<String, Object>> getMap (List<CSVRecord> records, Map<String, Integer> headers) { Map<Integer, String> headerMap = formatHeaderMap(headers); List<Map<String, Object>> data = new ArrayList<>(); for (int i = 1; i < records.size(); i++) { Map<String, Object> map = new HashMap<>(); try { CSVRecord record = records.get(i)
GitHub
github.com › apache › commons-csv
GitHub - apache/commons-csv: Apache Commons CSV · GitHub
The Apache Commons CSV library provides a simple interface for reading and writing CSV files of various types.
Starred by 412 users
Forked by 304 users
Languages Java 99.8% | Shell 0.2%
Frequal
frequal.com › java › ApacheCommonsCsvForEasyJavaCsvParsing.html
Apache Commons CSV for Easy CSV Parsing in Java
April 1, 2025 - Reader reader = new FileReader("folder/example.csv"); Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(reader); for (CSVRecord record : records) { String address = record.get("Address"); String city = record.get("City"); String state = record.get("State"); } I have used Apache Commons CSV and it is easy, quick, and powerful.
Javadoc.io
javadoc.io › doc › org.apache.commons › commons-csv › 1.6 › org › apache › commons › csv › CSVParser.html
CSVParser (Apache Commons CSV 1.6 API)
Latest version of org.apache.commons:commons-csv · 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 ·
Apache Commons
commons.apache.org › csv
Home – Apache Commons CSV
July 30, 2025 - Apache Commons, Apache Commons CSV, Apache, the Apache logo, and the Apache Commons project logos are trademarks of The Apache Software Foundation.
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 - Let's now read the content of the generated CSV file using the following program: 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").withIgnoreHeaderCa