Java - Write hashmap to a csv file -


i have hashmap string key , string value. contains large number of keys , respective values.

for example:

key | value abc | aabbcc def | ddeeff 

i write hashmap csv file such csv file contains rows below:

abc,aabbcc def,ddeeff 

i tried following example here using supercsv library: http://javafascination.blogspot.com/2009/07/csv-write-using-java.html. however, in example, have create hashmap each row want add csv file. have large number of key value pairs means several hashmaps, each containing data 1 row need created. know if there more optimized approach can used use case.

thanks in advance!

as question asking how using super csv, thought i'd chime in (as maintainer of project).

i thought iterate on map's entry set using csvbeanwriter , name mapping array of "key", "value", doesn't work because hashmap's internal implementation doesn't allow reflection key/value.

so option use csvlistwriter follows. @ least way don't have worry escaping csv (every other example here joins 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)){         (map.entry<string, string> entry : map.entryset()){             listwriter.write(entry.getkey(), entry.getvalue());         }     }      system.out.println(output); } 

output:

abc,aabbcc def,ddeeff 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -