Search code examples
javacsv

How to write HashMap to CSV?


I have a method countOcc() which prints a list (below).

1:00 ==> 1 hits(s)
2:00 ==> 4 hits(s)
3:00 ==> 3 hits(s)
4:00 ==> 6 hits(s)
5:00 ==> 14 hits(s)
6:00 ==> 26 hits(s)
7:00 ==> 16 hits(s)
8:00 ==> 25 hits(s)
9:00 ==> 34 hits(s)
10:00 ==> 39 hits(s)
11:00 ==> 33 hits(s)
12:00 ==> 50 hits(s)
13:00 ==> 49 hits(s)
14:00 ==> 51 hits(s)
15:00 ==> 53 hits(s)
16:00 ==> 40 hits(s)
17:00 ==> 20 hits(s)
18:00 ==> 33 hits(s)
19:00 ==> 26 hits(s)
20:00 ==> 18 hits(s)
21:00 ==> 29 hits(s)
22:00 ==> 7 hits(s)

method:

public void countOcc(ArrayList<Integer> list) {

    String aout = new String();
    System.out.println("\n");

    Integer[] numbers = list.toArray(new Integer[list.size()]);

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < numbers.length; i++) {
        int key = numbers[i];
        if (map.containsKey(key)) {
            int occurrence = map.get(key);
            occurrence++;
            map.put(key, occurrence);
        } else {
            map.put(key, 1);
        }
    }

    Iterator iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
        int key = (Integer) iterator.next();
        int occurrence = map.get(key);

         System.out.println(key+":00"+ " ==> " + occurrence + " hits(s)");


    }        

}

I'd like to have a csv file on its output:

1:00,2:00,3:00,4:00,5:00,6:00,7:00,8:00,9:00,10:00,11:00,12:00
1,4,3,6,14,26,16,25,34,39,33,50

I know about opencsv but I don't really know how to use it with HashMap.


Solution

  • Have you looked into SuperCSV? The framework has a built in CsvMapWriter: http://super-csv.github.io/super-csv/examples_writing.html

    You basically define your header as an array (you can take the map's sorted keyset for that) and then simply write the map using:

    mapWriter.write(map, header, processors);