0

I have a hashmap with a String key and List(String) as values.

For Example:

Key | Values
John | GroupName1,GroupName2,GroupName3
Nick | Groupname4,GroupName1

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

John,GroupName1,GroupName2,GroupName3    
Nick,Groupname4,GroupName1

I tried:

Map<String, List<String>> usersmap = (Map<String, List<String>>) model.get("users"); //this is my map
StringWriter output = new StringWriter();
ICsvListWriter listWriter;
listWriter = new CsvListWriter(output, CsvPreference.STANDARD_PREFERENCE);
for (Map.Entry<String, List<String>> entry : usersmap.entrySet()) {
    listWriter.write(entry.getKey(), entry.getValue());
}

but it doesn't seem right to me.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    Can you specify "doesn't seem right" ? – khelwood Jun 05 '18 at 14:07
  • Are you getting any error message? – Vinit Mehta Jun 05 '18 at 14:09
  • Yes of Course.I mean that listWriter.write can take a String -->key and a List --> entry.getValue() as arguments? or i need to pass two strings? My problem is the List – giannis gouziokas Jun 05 '18 at 14:12
  • 1
    The thing is that you are breaking the CSV concept. Keys should be the header of your file and the Values should be the line under the keys. Why don't you just use a OutputStreamWriter to make what you want ? – GabLeg Jun 05 '18 at 14:16
  • In the Documentation of CsvListWriter Class i found this : write(String... columns) -->Writes an array of strings as columns of a CSV file. So, if i create a new list inside the loop and "merge" the key and values as a new List , it will work? – giannis gouziokas Jun 05 '18 at 14:20
  • My problem is that when a user downloads the csv-file and opens it in excel i want the following format: first row{ first column: John(its the key) second column: GroupName1 third column: GroupName2 etc...} second row{ first column:Nick(its the key) second column: GroupName third column: otherGroupName etc...} – giannis gouziokas Jun 05 '18 at 14:30

1 Answers1

0

Try to convert your List into a comma separated string using String.join(...)

listWriter.write(entry.getKey(), String.join(",", entry.getValue());

Java documentation:

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-

Bilal EL CHAMI
  • 414
  • 1
  • 3
  • 14