If you have a situation where you need to write data to CSV file, one option should be using apache commons library. If you're using Maven, first you'll need to add dependency into pom.xml:


Get Gayle Laakmann - Cracking the Coding Interview - 4th, 5th and 6th edition

Code sample

Following code contains a solution for this issue:


import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

public class ExportDataToCsv {
	private static final String SAMPLE_CSV_FILE = "./sample.csv";
	public void exportDataToCsv() throws IOException {
		BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));
		CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("customerId", "locationId"));
		Map<String, String> data = new HashMap<String, String>();
		for (Map.Entry<String, String> entry : data.entrySet()) {
			csvPrinter.printRecord(Arrays.asList(entry.getKey(), entry.getValue()));

 You can find this code also on github.