简体   繁体   English

遍历HashMap的HashMap

[英]Iterating over HashMap of HashMap

Why is this wrong? 为什么会这样呢?

for (Entry<String, HashMap> temp : wordCountforFile.entrySet()) {
        System.out.println(temp.getKey());
        for(Entry<String, Integer> temp1: temp.getValue()){
            //Wrong?
        }
    }

where: HashMap wordCountforFile = new HashMap(); 其中:HashMap wordCountforFile = new HashMap();

HashMap<String, Integer> wordCount = new HashMap<String, Integer>();

and

wordCountforFile.put("Any String", wordCount);

This is wrong because you didn't specify the generics for the HashMap temp . 这是错误的,因为您没有为HashMap temp指定泛型。 Also, you should iterate over the entrySet() in the innermost loop if you're expecting a Map.Entry . 另外,如果您希望获得Map.Entry ,则应该在最内部的循环中迭代entrySet() You should use: 您应该使用:

for (Entry<String, HashMap<String, Integer>> temp : wordCountforFile.entrySet()) {
    System.out.println(temp.getKey());
    for(Entry<String, Integer> temp1 : temp.entrySet()){
        // ...
    }
}

As a side note, I typically find that if you have a Map of a Map, it means that one of those maps logically represents some kind of entity that can be simplified if you were to move it to its own class. 附带说明一下,我通常会发现,如果您有一个Map的Map,这意味着这些地图中的一个在逻辑上代表了某种实体,如果要将其移动到其自己的类中,则可以简化该实体。 Just a thought. 只是一个想法。

    HashMap<String, HashMap<String, Integer>> wordCountforFile = new HashMap<String, HashMap<String, Integer>>();

    HashMap<String, Integer> wordCount = new HashMap<String, Integer>();

    wordCountforFile.put("Any String", wordCount);

    for (Map.Entry<String, HashMap<String, Integer>> temp : wordCountforFile.entrySet()) {
        System.out.println(temp.getKey());
        for(Map.Entry<String, Integer> temp1: temp.getValue().entrySet()){

        }
    }
 }

wordCountForFile is not defined with generics. wordCountForFile未使用泛型定义。 without generics an explicit type casting should be done. 如果没有泛型,则应进行显式类型转换。

   for(Map.Entry<String, HashMap<String, Integer>> temp : ((Set<Map.Entry<String, HashMap<String, Integer>>>) wordCountforFile.entrySet()))

But this is not always safe because it can cause ClassCastException if an entry is not of type String & HashMap. 但这并不总是安全的,因为如果条目不是String&HashMap类型,则可能导致ClassCastException。 It is always better to use generics if the type of key and value in a map is known to avoid ClassCastException. 如果已知映射中的键和值的类型可以避免ClassCastException,则最好使用泛型。

temp.getValue() returns a map of String & Integer.If you want to iterate through each entry in this map use temp.getValue().entrySet() temp.getValue()返回String和Integer的映射。如果要遍历此映射中的每个条目,请使用temp.getValue()。entrySet()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM