Java - Write hashmap to a csv file

activelearner picture activelearner · Jul 1, 2015 · Viewed 36.9k times · Source

I have a hashmap with a String key and String value. It contains a large number of keys and their respective values.

For example:

key | value
abc | aabbcc
def | ddeeff

I would like to write this hashmap to a csv file such that my csv file contains rows as below:

abc,aabbcc
def,ddeeff

I tried the following example here using the supercsv library: http://javafascination.blogspot.com/2009/07/csv-write-using-java.html. However, in this example, you have to create a hashmap for each row that you want to add to your csv file. I have a large number of key value pairs which means that several hashmaps, with each containing data for one row need to be created. I would like to know if there is a more optimized approach that can be used for this use case.

Answer

Ajay Kumar picture Ajay Kumar · Aug 3, 2016

Using the Jackson API, Map or List of Map could be written in CSV file. See complete example here

 /**
 * @param listOfMap
 * @param writer
 * @throws IOException
 */
public static void csvWriter(List<HashMap<String, String>> listOfMap, Writer writer) throws IOException {
    CsvSchema schema = null;
    CsvSchema.Builder schemaBuilder = CsvSchema.builder();
    if (listOfMap != null && !listOfMap.isEmpty()) {
        for (String col : listOfMap.get(0).keySet()) {
            schemaBuilder.addColumn(col);
        }
        schema = schemaBuilder.build().withLineSeparator(System.lineSeparator()).withHeader();
    }
    CsvMapper mapper = new CsvMapper();
    mapper.writer(schema).writeValues(writer).writeAll(listOfMap);
    writer.flush();
}