Search code examples
javacsvhashmapsupercsv

Java - Write hashmap to a csv file


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.


Solution

  • As your question is asking how to do this using Super CSV, I thought I'd chime in (as a maintainer of the project).

    I initially thought you could just iterate over the map's entry set using CsvBeanWriter and a name mapping array of "key", "value", but this doesn't work because HashMap's internal implementation doesn't allow reflection to get the key/value.

    So your only option is to use CsvListWriter as follows. At least this way you don't have to worry about escaping CSV (every other example here just joins with commas...aaarrggh!):

    @Test
    public void writeHashMapToCsv() throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("abc", "aabbcc");
        map.put("def", "ddeeff");
    
        StringWriter output = new StringWriter();
        try (ICsvListWriter listWriter = new CsvListWriter(output, 
             CsvPreference.STANDARD_PREFERENCE)){
            for (Map.Entry<String, String> entry : map.entrySet()){
                listWriter.write(entry.getKey(), entry.getValue());
            }
        }
    
        System.out.println(output);
    }
    

    Output:

    abc,aabbcc
    def,ddeeff