我有一個方法countOcc()
,它打印一個列表(如下)。如何將HashMap寫入CSV?
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)
方法:
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)");
}
}
我想有它的輸出csv文件:
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
我知道opencsv,但我真的不知道如何使用它與HashMap。
見溶液(http://stackoverflow.com/a/38749527/2685581) – Ajay