views:

228

answers:

6

Possible Duplicates:
Java: Efficient Equivalent to Removing while Iterating a Collection
Removing items from a collection in java while iterating over it

I'm trying to loop through HashMap:

Map<String, Integer> group0 = new HashMap<String, Integer>();

... and extract every element in group0. This is my approach:

// iterate through all Members in group 0 that have not been assigned yet
for (Map.Entry<String, Integer> entry : group0.entrySet()) {

    // determine where to assign 'entry'
    iEntryGroup = hasBeenAccusedByGroup(entry.getKey());
    if (iEntryGroup == 1) {
        assign(entry.getKey(), entry.getValue(), 2);
    } else {
        assign(entry.getKey(), entry.getValue(), 1);
    }
}

The problem here is that each call to assign() will remove elements from group0, thus modifying its size, thus causing the following error:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$EntryIterator.next(HashMap.java:834)
    at java.util.HashMap$EntryIterator.next(HashMap.java:832)
    at liarliar$Bipartite.bipartition(liarliar.java:463)
    at liarliar$Bipartite.readFile(liarliar.java:216)
    at liarliar.main(liarliar.java:483)

So... how can I loop through the elements in group0 while its dynamically changing?

Thanks.

A: 

You need to use the actual iterator and its remove method if you want to modify the collection while looping over it. There isn't really any way to do it with the foreach construct.

If you're trying to remove multiple entries in one iteration, you'll need to loop over something that's not backed by the map.

Set<String> keys = new HashSet<String>(group0.keySet());
for (String key : keys) {
  if (group0.containsKey(key)) {
    Integer value = group0.get(key);
    //your stuff 
  }
}
Affe
`assign()` can also potentially remove more than 1 elements from group0... so there is the chance where one iteration will remove all elements in group0 and no need for a second iteration. Can you post code for how the Iterator works?
Hristo
+1  A: 

In this case, how can assign modify group0? More details are needed. Typically you cannot modify a collection while iterating over it. You modify through the Iterator interface.

fastcodejava
+1  A: 

You could use a ConcurrentHashMap

Kevin Williams
@Kevin... interesting. Thanks for the suggestion. Could you briefly touch on the performance benefits of using a ConcurrentHashMap? Are there significant improvements in using such a data structure, in terms of checking if an element exists, getting an element, removing an element, inserting an element, etc...?
Hristo
+1  A: 

In your particular case I would not modify the structure of the HashMap but merely null the value you want to remove. Then if you end up visiting a null value just skip it.

In the general case I prefer to use a Stack for things like this because they're particularly easy to visualise and so I tend to have less issues with border conditions (just keeping popping 'till empty).

CurtainDog
ahh... good idea :) but using a stack is completely incorrect here... for example if I wanted to check if an element exists, that would be ridiculously inefficient here. For my goal, efficiency and speed is a must. but I like the idea of null-ing. +1
Hristo
+1  A: 

Others have mentioned the correct solution without actually spelling it out. So here it is:

Iterator<Map.Entry<String, Integer>> iterator = 
    group0.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();

    // determine where to assign 'entry'
    iEntryGroup = hasBeenAccusedByGroup(entry.getKey());

    if (iEntryGroup == 1) {
        assign(entry.getKey(), entry.getValue(), 2);
    } else {
        assign(entry.getKey(), entry.getValue(), 1);
    }

    // I don't know under which conditions you want to remove the entry
    // but here's how you do it
    iterator.remove();
}

Also, if you want to safely change the map in your assign function, you need to pass in the iterator (of which you can only use the remove function and only once) or the entry to change the value.

seanizer
Thanks...this is exactly what I'm looking for!
Hristo