Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

Comma-separated value (CSV) files are easy to work with and applicable in various applications regarding data storing and exchanging. Java developers, at some point, have to export data to CSVs when handling data structures like HashMaps.

In this tutorial, we’ll learn how to write HashMap to a CSV file.

2. Writing HashMap to CSV Manually

To write data into the “employee_data.csv” file, we’ll use the help of the FileWriter class. Afterward, each row of employee data is inserted into separate EmployeeData cells. Here’s the code that accomplishes this:

Map<String, String> employeeData = new HashMap<>();
employeeData.put("Name", "John Doe");
employeeData.put("Title", "Software Engineer");
employeeData.put("Department", "Engineering");
employeeData.put("Salary", "75000");
try (FileWriter csvWriter = new FileWriter("employee_data.csv")) {
    // Write header row
    csvWriter.append("Name,Title,Department,Salary\n");

    // Write data row
    csvWriter.append(employeeData.get("Name")).append(",");
    csvWriter.append(employeeData.get("Title")).append(",");
    csvWriter.append(employeeData.get("Department")).append(",");
    csvWriter.append(employeeData.get("Salary")).append("\n");

    // Close the csvWriter to save the data
    csvWriter.close();
} catch (IOException e) {
    e.printStackTrace();
}

In the above code, we created row headers and then traversed the employeeData Hashmap to append each key value as a CSV row delimited by a comma. After completing the data write operation, we close the csvWriter to save the data. And then, finally, the code tries to handle exceptions.

3. Writing HashMap to CSV Using Apache Commons CSV

Working with CSV files in Java is a robust and efficient endeavor using the Apache Commons CSV library. To write HashMap data to a CSV file, we should first add the following dependency to our project’s pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.10.0</version>
</dependency>

Now, let’s see how to retrieve data from a CSV using the Apache Commons library:

try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter("employee_data2.csv"), CSVFormat.DEFAULT)) {
    // Write header row
    csvPrinter.printRecord("Name", "Title", "Department", "Salary");

    // Write data row
    csvPrinter.printRecord(employeeData.get("Name"), employeeData.get("Title"), employeeData.get("Department"), employeeData.get("Salary"));
} catch (IOException e) {
    e.printStackTrace();
}

// Ensure the CSV file exists
assertTrue(new File("employee_data2.csv").exists());

In the above code, we initialize a CSVPrinter and create a new FileWriter object to identify where the output CSV file is expected. Subsequently, we iterate through the HashMap using the CSVPrinter to put its content into the CSV file. Lastly, we close both CSVPrinter and FileWriter to ensure that the data is properly flushed and saved as required.

4. Conclusion

In conclusion, we have learned that it is possible for us to generate and write HashMap into a CSV File by means of assertion while asserting the proof of our implementation in Java.

To be specific, this skill is used in various data-related activities like transferring data towards more detailed analyses, report creation, and migration.

As always, the complete code samples for this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.