Reputation: 21
I have a HashMap declared as
static HashMap<String,ArrayList<Integer>> inverted_index = new HashMap<String,ArrayList<Integer>>();
I iterated over its keys as
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();
}
I did all this in a function called printInvertedIndex(). Now in some other function I want to iterate over the HashMap again, so I did this
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();
}
}
But I am not getting "here" printed while calling createPermutermIndex(). That is, my iterator is not iterating over the entries of inverted_index.
Is there any way I can iterate over it again?
Upvotes: 1
Views: 1504
Reputation: 20159
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
writer.println(pair.getKey() + " " + pair.getValue());
it.remove(); // <- This is your problem
}
You're removing the entries while you're iterating through them. When the loop exits, you will have deleted all the entries in the map. Therefore, it's not surprising that the second loop doesn't do anything - there is nothing left to iterate over.
It doesn't seem like you want to remove anything during these loops, so just remove those it.remove()
lines in your two loops.
Upvotes: 7