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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Mapping header names to indices decouples parsing from a fixed column order.
- 2try-with-resources guarantees the reader closes even when parsing throws.
- 3Validating field counts before access turns silent corruption into a clear, located error.
Related explainers
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-a-csv-into-typed-objects-in-java-explained-java-f26d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.