Code Review: Improve a Java Method That Builds a CSV String
MercorSoftware Engineer · Technical ScreenLast updated
A Java code-reading question: review a short method that concatenates a list of rows into a CSV string and propose improvements. It tests knowledge of string-building performance, separator and escaping rules for CSV, null handling, streaming output for large exports, and risks when files are opened in spreadsheets.
The interviewer shows the following Java method and asks what improvements you would make. There is no coding in this round: explain the problems you see and how you would fix them.
public String buildCsv(List<List<String>> rows) {
String s = "";
for (List<String> row : rows) {
for (String cell : row) {
s += cell + ",";
}
s += "\n";
}
return s;
}
Clarifying Questions
- Who consumes the output: a spreadsheet application, another service, a file download? Which CSV conventions and line endings does it expect?
- Can cells contain commas, double quotes or line breaks? Can a cell or a row be
null? - How large can the input be, and must the result be one
String, or could it be written to a file or a response stream? - Do all rows have the same number of cells, and is there a header row?
Hints
Hint 1
Count the copies: Java strings are immutable. Think about how much copying the loop performs as the output grows.
Hint 2
Feed it awkward cells: Try a cell that contains a comma, a double quote or a line break, and read the output the way a CSV parser would.
Follow-up questions
- The export must handle tables too large to hold in memory. How do the signature and the implementation change?
- Which test cases would you write for this method?
- Would you write this yourself or use a CSV library, and what would decide it?
- How would you protect users who open the exported file in a spreadsheet application from cells that look like formulas?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.