无法将 foreach 从 C# 转换为 Java

Can't translate foreach from C# to Java

我正在尝试翻译 Boolean Retrieval Model search engine,但无法将这段代码翻译成 Java。

C#:

foreach(KeyValuePair<string ,List<string>> p in documentCollection){}

Java:

for(Map<String, ArrayList<String>> p : documentCollection){}
            

不幸的是 Java 给我这个错误:

for-each not applicable to application type

提前致谢!

C# 的 IDictionary<K,V> 和 Java 的 Map<K,V> 实现集合接口的方式有所不同。在 C# 中,可以为键值对枚举集合本身;在Java中,必须调用一个方法来获取key-value集合,叫做entrySet():

for (Map.Entry<String,ArrayList<String>> p : documentCollection.entrySet()) {
    ...
}

请注意,在 Java 中,您迭代 Map.Entry<K,V> 个对象而不是 C# 的 KeyValuePair<K,V>