
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.
Commercials Cooperation Advertisements:
(1) IT Teacher IT Freelance

立刻註冊及報名電腦補習課程吧!
电子计算机 -教育 -IT 電腦班” ( IT電腦補習 ) 提供一個方便的电子计算机 教育平台, 為大家配對信息技术, 電腦 老師, IT freelance 和 programming expert. 讓大家方便地就能找到合適的電腦補習, 電腦班, 家教, 私人老師.
We are a education and information platform which you can find a IT private tutorial teacher or freelance.
Also we provide different information about information technology, Computer, programming, mobile, Android, apple, game, movie, anime, animation…
(2) ITSec
www.ITSeceu.uk
Secure Your Computers from Cyber Threats and mitigate risks with professional services to defend Hackers.
ITSec provide IT Security and Compliance Services, including IT Compliance Services, Risk Assessment, IT Audit, Security Assessment and Audit, ISO 27001 Consulting and Certification, GDPR Compliance Services, Privacy Impact Assessment (PIA), Penetration test, Ethical Hacking, Vulnerabilities scan, IT Consulting, Data Privacy Consulting, Data Protection Services, Information Security Consulting, Cyber Security Consulting, Network Security Audit, Security Awareness Training.
Contact us right away.
Email (Prefer using email to contact us):
SalesExecutive@ITSec.vip