【问题标题】:Printing out a hash map that contains another hash map打印出包含另一个哈希映射的哈希映射
【发布时间】:2013-11-23 17:41:41
【问题描述】:

我正在开发一个程序,该程序接收 X 数量的文件,然后使用多线程计算每个文件中单词的出现次数,并将结果保存在哈希映射中。

Map<String, Map<String, Integer>>

我有一个像上面这样的散列映射,格式为 我想将整个地图导出到文本文件并保存。

是否有打印整个地图的简单解决方案(顺序/排序无关紧要)?

【问题讨论】:

标签: java string hash hashmap


【解决方案1】:

如果你想自己做,你可以:

Map<String, Map<String, Integer>> dictionaries = null;

PrintWriter pw = null;

for(Map.Entry<String, Map<String, Integer>> dictionaryEntry : dictionaries.entrySet()) {

    for(Map.Entry<String, Integer>  wordCounts :  dictionaryEntry.getValue().entrySet()) {

        pw.print(dictionaryEntry.getKey() + ", " + wordCounts.getKey() + ", " + wordCounts.getValue());

    }

}

HashMap 是可序列化的,所以你可以使用

ObjectOutputStream : http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html

【讨论】:

    【解决方案2】:

    这里map 包含filename --&gt; another map

    m 包含word-------&gt; count

       Map<String, Map<String, Integer>> map = new HashMap<String, Map<String, Integer>>();
        Map<String, Integer> m = new HashMap<String, Integer>();
        m.put("abcd", 34);
        m.put("xyz", 34);
        map.put("a.txt", m);
    
        m=new HashMap<String, Integer>();
        m.put("abcd", 34);
        m.put("xyz", 34);
        map.put("b.txt", m);
    
        for(String s : map.keySet()){
            System.out.println("File name: "+s);
            Map<String, Integer> innerMap = map.get(s);
            for(String str:innerMap.keySet()){
                System.out.println(str+" : "+innerMap.get(str));
            }
            System.out.println("--------------------------------------------------------------------------------");
        }
    

    输出:

    File name: b.txt
    abcd : 34
    xyz : 34
    --------------------------------------------------------------------------------
    File name: a.txt
    abcd : 34
    xyz : 34
    

    或者另一种方式就是你喜欢:

    System.out.println(map);
    

    输出:

    {b.txt={abcd=34, xyz=34}, a.txt={abcd=34, xyz=34}}
    

    【讨论】:

      【解决方案3】:

      当然,有多种方法可以做到这一点。我最喜欢的是使用google-gson。它是一个在 JSON 和 Java 对象之间转换的 Java 库。因此,您将能够轻松检索嵌套的哈希映射结构,并且无需(嗯...... 1-2 行)额外的编码。

      这是detailed gson example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-13
        • 1970-01-01
        • 1970-01-01
        • 2016-08-04
        • 2016-04-23
        • 1970-01-01
        相关资源
        最近更新 更多