如何将HashMap写入CSV? [英] How to write HashMap to CSV?

查看:177
本文介绍了如何将HashMap写入CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法 countOcc()打印一个列表(下面)。

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)

方法:

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文件在其输出:

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

我知道opencsv,但我不知道真的知道如何使用HashMap。

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

推荐答案

你看过SuperCSV吗?该框架有一个内置的CsvMapWriter:
http:// super-csv .github.io / super-csv / examples_writing.html

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);

这篇关于如何将HashMap写入CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆