[英]Iterating twice over HashMap Java
我有一个HashMap声明为
static HashMap<String,ArrayList<Integer>> inverted_index = new HashMap<String,ArrayList<Integer>>();
我遍历了它的键
public static void printInvertedIndex() throws FileNotFoundException{
PrintWriter writer = new PrintWriter(new File("InvertedIndex.txt"));
Iterator it = inverted_index.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
writer.println(pair.getKey() + " " + pair.getValue());
it.remove();
}
writer.close();
}
我在名为printInvertedIndex()的函数中完成了所有这些操作。 现在在其他函数中,我想再次遍历HashMap,所以我这样做了
public static void createPermutermIndex(){
permuterm_index.clear();
Iterator it = inverted_index.entrySet().iterator();
while (it.hasNext()) {
System.out.println("here");
Map.Entry pair = (Map.Entry)it.next();
String temp;
temp = pair.getKey() + "$";
ArrayList<String> perms = rotations(temp);
System.out.println(perms.size());
for(int i=0; i<perms.size(); i++)
System.out.println(perms.get(i));
//permuterm_index.put(temp, perms.get(i));
it.remove();
}
}
但是我在调用createPermutermIndex()时并没有得到“这里”的打印。 就是说,我的迭代器没有迭代反向索引的条目。
有什么办法可以再次迭代吗?
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
writer.println(pair.getKey() + " " + pair.getValue());
it.remove(); // <- This is your problem
}
您正在遍历它们的同时删除这些条目。 循环退出时,您将删除映射中的所有条目。 因此,第二个循环不做任何事情也就不足为奇了-无需进行任何迭代。
似乎您不想在这些循环中删除任何内容,因此只需在两个循环中删除那些it.remove()
行即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.