java 43 lines · 7 steps

Parsing a CSV into typed objects in Java

A header-driven CSV parser maps column names to indices so rows become Employee objects regardless of column order.

Explained by highlit
1public List<Employee> parseEmployees(Path csvPath) throws IOException {
2 List<Employee> employees = new ArrayList<>();
3 
4 try (BufferedReader reader = Files.newBufferedReader(csvPath, StandardCharsets.UTF_8)) {
5 String headerLine = reader.readLine();
6 if (headerLine == null) {
7 return employees;
8 }
9 
10 String[] headers = splitCsvLine(headerLine);
11 Map<String, Integer> columns = new HashMap<>();
12 for (int i = 0; i < headers.length; i++) {
13 columns.put(headers[i].trim().toLowerCase(), i);
14 }
15 
16 String line;
17 int lineNumber = 1;
18 while ((line = reader.readLine()) != null) {
19 lineNumber++;
20 if (line.isBlank()) {
21 continue;
22 }
23 
24 String[] fields = splitCsvLine(line);
25 if (fields.length < columns.size()) {
26 throw new IllegalStateException("Malformed row at line " + lineNumber);
27 }
28 
29 Employee employee = new Employee(
30 fields[columns.get("id")].trim(),
31 fields[columns.get("name")].trim(),
32 new BigDecimal(fields[columns.get("salary")].trim())
33 );
34 employees.add(employee);
35 }
36 }
37 
38 return employees;
39}
40 
41private String[] splitCsvLine(String line) {
42 return line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Mapping header names to indices decouples parsing from a fixed column order.
  2. 2try-with-resources guarantees the reader closes even when parsing throws.
  3. 3Validating field counts before access turns silent corruption into a clear, located error.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing a CSV into typed objects in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code