2

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.

XorOrNor
  • 8,868
  • 12
  • 48
  • 81

5 Answers5

2

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);
nutfox
  • 484
  • 3
  • 13
0

As this article explains, writing to a CSV file is just like writing to a text file.

public static void write()
{
     StringBuilder out = new StringBuilder();
     for (int key : map.keySet())
     {
         out.append(key + ":00,");
     }

     // remove last ',' from line
     out = new StringBuilder(out.substring(0, out.length() - 1));

     for (int occurence : map.values())
     {
         out.append(occurence + ",");
     }

     // remove last ',' from line
     out = new StringBuilder(out.substring(0, out.length() - 1));

     try (FileWriter fw = new FileWriter("my.csv"))
     {
         writer.append(out.toString());
     }
     catch (IOException e)
     {
         e.printStackTrace();
     }
}
Rossiar
  • 2,416
  • 2
  • 23
  • 32
0

Cribbing off this opencsv tutorial:

Map<String, String> values = new HashMap<>();
for (String line : lines) {
    String[] parts = line.split(" ");
    String time = parts[0];
    String value = parts[2];
    values.put(time, value);
}
StringWriter writer_ = new StringWriter();
CSVWriter writer = new CSVWriter(writer_);
writer.writeNext(values.keySet().toArray());
writer.writeNext(values.values().toArray());
writer.close();
System.out.println(writer_.toString());

This gives your output.

hd1
  • 33,938
  • 5
  • 80
  • 91
  • 3
    The order of the keySet() and values() method calls are not guaranteed to be the same. So you could end up with headers that don't match the content rows - also your header wouldn't be sorted. – nutfox Jul 20 '15 at 08:33
  • It gave me the order OP showed, and does so consistently. *shrug* – hd1 Jul 20 '15 at 08:35
0

You might need this:

  public static void countOcc(List<Integer> list) {
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer key : list) {
            if (map.containsKey(key)) {
                map.put(key, map.get(key) + 1);
            } else {
                map.put(key, 1);
            }
        }

        String csv = "d://data.csv";
        try (CSVWriter writer = new CSVWriter(new FileWriter(csv))) {
            String[] keysArray = new String[map.keySet().size()];
            String[] valuesArray = new String[map.values().size()];
            int counter = 0;
            for (Entry<Integer, Integer> entry : map.entrySet()) {
                keysArray[counter] = entry.getKey() + ":00";
                valuesArray[counter] = entry.getValue() + "";
                counter++;
            }
            writer.writeNext(keysArray);
            writer.writeNext(valuesArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
-1

here is the example of writing to a CSV file you may customize it accordingly:

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


    public class CsvFileWriter {


    //Delimiter used in CSV file
    private static final String COMMA_DELIMITER = ",";
    private static final String NEW_LINE_SEPARATOR = "\n";

    //CSV file header
    private static final String FILE_HEADER = "id,firstName,lastName,gender,age";

    public static void writeCsvFile(String fileName) {

        //Create new students objects
        Student student1 = new Student(1, "Ahmed", "Mohamed", "M", 25);
        Student student2 = new Student(2, "Sara", "Said", "F", 23);
        Student student3 = new Student(3, "Ali", "Hassan", "M", 24);
        Student student4 = new Student(4, "Sama", "Karim", "F", 20);
        Student student5 = new Student(5, "Khaled", "Mohamed", "M", 22);
        Student student6 = new Student(6, "Ghada", "Sarhan", "F", 21);

        //Create a new list of student objects
        List students = new ArrayList();
        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);
        students.add(student5);
        students.add(student6);

        FileWriter fileWriter = null;

        try {
            fileWriter = new FileWriter(fileName);

            //Write the CSV file header
            fileWriter.append(FILE_HEADER.toString());

            //Add a new line separator after the header
            fileWriter.append(NEW_LINE_SEPARATOR);

            //Write a new student object list to the CSV file
            for (Student student : students) {
                fileWriter.append(String.valueOf(student.getId()));
                fileWriter.append(COMMA_DELIMITER);
                fileWriter.append(student.getFirstName());
                fileWriter.append(COMMA_DELIMITER);
                fileWriter.append(student.getLastName());
                fileWriter.append(COMMA_DELIMITER);
                fileWriter.append(student.getGender());
                fileWriter.append(COMMA_DELIMITER);
                fileWriter.append(String.valueOf(student.getAge()));
                fileWriter.append(NEW_LINE_SEPARATOR);
            }



            System.out.println("CSV file was created successfully !!!");

        } catch (Exception e) {
            System.out.println("Error in CsvFileWriter !!!");
            e.printStackTrace();
        } finally {

            try {
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                System.out.println("Error while flushing/closing fileWriter !!!");
                e.printStackTrace();
            }

        }
    }
    }
Piyush Mittal
  • 1,860
  • 1
  • 21
  • 39
  • I don't see why you would write this yourself if you can reuse an existing and well tested framework. In addition: Your code should not use a hard coded line separator - you should use the system's value for this - otherwise your code only works in Windows and not in e.g. Linux (or the other way around). – nutfox Jul 20 '15 at 08:36