12

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
activelearner
  • 7,055
  • 20
  • 53
  • 94

6 Answers6

13

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();
}
Ajay Kumar
  • 4,864
  • 1
  • 41
  • 44
  • Somehow I keep getting this error:java.lang.NoSuchFieldError: USE_FAST_DOUBLE_WRITER at com.fasterxml.jackson.dataformat.csv.CsvGenerator.(CsvGenerator.java:248) at com.fasterxml.jackson.dataformat.csv.CsvFactory._createGenerator(CsvFactory.java:455) – Abhinash Jha Jul 02 '23 at 08:25
12

Something like this should do the trick:

String eol = System.getProperty("line.separator");

try (Writer writer = new FileWriter("somefile.csv")) {
  for (Map.Entry<String, String> entry : myHashMap.entrySet()) {
    writer.append(entry.getKey())
          .append(',')
          .append(entry.getValue())
          .append(eol);
  }
} catch (IOException ex) {
  ex.printStackTrace(System.err);
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
4

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
James Bassett
  • 9,458
  • 4
  • 35
  • 68
  • Can you please tell me what are the libraries I need to import for this? or Do I need to write any other method to run this or can I use it as it is? – RV_Dev Feb 27 '17 at 14:03
1
 Map<String, String> csvMap = new TreeMap<>();
        csvMap.put("Hotel Name", hotelDetails.getHotelName());
        csvMap.put("Hotel Classification", hotelDetails.getClassOfHotel());
        csvMap.put("Number of Rooms", hotelDetails.getNumberOfRooms());
        csvMap.put("Hotel Address", hotelDetails.getAddress());


        // specified by filepath
        File file = new File(fileLocation + hotelDetails.getHotelName() + ".csv");

        // create FileWriter object with file as parameter
        FileWriter outputfile = new FileWriter(file);

        String[] header = csvMap.keySet().toArray(new String[csvMap.size()]);
        String[] dataSet = csvMap.values().toArray(new String[csvMap.size()]);

        // create CSVWriter object filewriter object as parameter
        CSVWriter writer = new CSVWriter(outputfile);


        // adding data to csv
        writer.writeNext(header);
        writer.writeNext(dataSet);


        // closing writer connection
        writer.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Sandun Susantha
  • 1,010
  • 1
  • 10
  • 11
0

If you have a single hashmap it is just a few lines of code. Something like this:

Map<String,String> myMap = new HashMap<>();

myMap.put("foo", "bar");
myMap.put("baz", "foobar");

StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> kvp : myMap.entrySet()) {
    builder.append(kvp.getKey());
    builder.append(",");
    builder.append(kvp.getValue());
    builder.append("\r\n");
}

String content = builder.toString().trim();
System.out.println(content);
//use your prefered method to write content to a file - for example Apache FileUtils.writeStringToFile(...) instead of syso.    

result would be

foo,bar
baz,foobar
dognose
  • 20,360
  • 9
  • 61
  • 107
0

My Java is a little limited but couldn't you just loop over the HashMap and add each entry to a string?

// m = your HashMap

StringBuilder builder = new StringBuilder();
for(Entry<String, String> e : m.entrySet()) 
{
    String key = e.getKey();
    String value = e.getValue();

    builder.append(key);
    builder.append(',');
    builder.append(value);
    builder.append(System.getProperty("line.separator"));
}

string result = builder.toString();
James
  • 419
  • 4
  • 25