【问题标题】:Problems in writing a file using Map<String, Map<String, Long>>使用 Map<String, Map<String, Long>> 写入文件的问题
【发布时间】:2016-06-14 10:38:44
【问题描述】:

我有一个格式如下Map&lt;String, Map&lt;String, Long&gt;&gt; map的数据结构:

1987 {abacate=1, catuaba, lion=3, coco=1, asas=2} 2005 {Polymer Science=3} 1234 {Environmental Studies=1}

每个 year 是我的 Hash 的关键,每一对 word=number 对应于我计算该单词出现次数的较早操作(用逗号分隔的那些是一个术语) .

我正在尝试遍历此哈希,以便我可以将每一对 word=number 用分隔符分隔,但由于这种结构,我的结果不是很一致。

当我使用简单的Map&lt;String, List&lt;String&gt;&gt; 时,我可以毫无问题地迭代和恢复我的所有键和值。使用map.forEach() 我能够做到这一点

map.forEach((name, lines) -> {
    try {
        Files.write(Paths.get(PATH), lines);`
    } catch (IOException e) {
        e.getStackTrace();
    }
});

但是现在在这个结构中我遇到了麻烦。有没有人有一个很好的方法来处理这个结构 (Map&lt;String, Map&lt;String, Long&gt;&gt;),所以我可以使用分隔符来编写它?

【问题讨论】:

  • 感谢@Dan W 修复我的格式

标签: java string file hash hashmap


【解决方案1】:

@Chill 响应的小变化(所有功劳归于他)

for (Entry<String, Map<String, Long>> mapEntry : props.entrySet()) {
            String mapKey = mapEntry.getKey();
            Map<String, Long> submap = mapEntry.getValue();
            for (Entry<String, Long> submapEntry : submap.entrySet()) {
                String submapKey = submapEntry.getKey();
                Long submapList = submapEntry.getValue();

                System.out.println(mapKey + "\t" + submapKey + "\t" + submapList);
                //TODO: do whatever you want with these items.
            }
        }

我的数据在 Map &lt;String, Map&lt;String, Long&gt;&gt; 中,所以我稍微修改了他的代码。

【讨论】:

    【解决方案2】:

    您可能只想在没有 lambda 的情况下遍历 Map 以了解您想要做什么。

        Map<String, Map<String, Long>> map = new HashMap<>();
    
        //...
    
        for (Entry<String, Map<String, Long>> mapEntry : map.entrySet()) {
            String mapKey = mapEntry.getKey();
            Map<String, Long> submap = mapEntry.getValue();
            for (Entry<String, Long> submapEntry : submap.entrySet()) {
                String submapKey = submapEntry.getKey();
                Long submapList = submapEntry.getValue();
    
                //TODO: do whatever you want with these items.
            }
        }
    

    【讨论】:

    • 好主意,我尝试压缩我的代码,结果一团糟。我会试试你的方法@Chill
    • 我的数据在 Map> 上,我正在尝试调整您的代码,但这是说我的结构不可迭代。我想它和你的很相似,但是入口地图应该是我的结构吧?
    • 我的Map&lt;String, List&lt;String&gt;&gt; 被转换成下面的Map&lt;String, Map&lt;String, Long&gt;&gt; props = count_hash_feat_rep.entrySet().stream().collect(toMap(Map.Entry::getKey, e -&gt; e.getValue().stream().collect(groupingBy(String::toString, counting())))); 所以当我尝试使用你的 for 时,它不会将我的props 识别为此操作的有效类型
    • 我在 for 循环中错过了 .entrySet()
    • 很好,让我再试一次。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 2021-11-09
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多