5

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 it's dynamically changing?

Community
  • 1
  • 1
Hristo
  • 45,559
  • 65
  • 163
  • 230
  • 2
    Make a copy of the group0 map and remove elements from the copy while looping through the group0? – sarahTheButterFly Aug 18 '10 at 23:57
  • @sarah... good point. I'll try that. – Hristo Aug 19 '10 at 00:01
  • @sarah... copying over group0 to a clone HashMap gives me the problem that when I remove from group0, I also remove from clone. How can I overcome that? How do I make an independent copy of group0? – Hristo Aug 19 '10 at 00:10
  • How do you make a copy? I would make a new map group0Clone and then adding elements one by one from group0. I am not sure if it works. I am trying it out too. – sarahTheButterFly Aug 19 '10 at 00:18
  • 2
    Similar questions: http://stackoverflow.com/questions/223918/java-efficient-equivalent-to-removing-while-iterating-a-collection, http://stackoverflow.com/questions/626671/java-how-to-remove-elements-from-a-list-while-iterating-over-adding-to-it, http://stackoverflow.com/questions/1622084/java-changing-the-properties-of-an-iterable-object-while-iterating-over-it, , http://stackoverflow.com/questions/1675037/removing-items-from-a-collection-in-java-while-iterating-over-it, http://stackoverflow.com/questions/993025/java-adding-elements-to-a-collection-during-iteration – Pascal Thivent Aug 19 '10 at 00:19
  • @ Hristo, I think we both can give up trying copying approach. :-) – sarahTheButterFly Aug 19 '10 at 00:24
  • But, anyway, I think this works too. Map group0Clone = new HashMap(); group0Clone.putAll(group0); – sarahTheButterFly Aug 19 '10 at 00:29
  • 1
    I've answered this before. See the accepted answer here: http://stackoverflow.com/questions/223918/java-efficient-equivalent-to-removing-while-iterating-a-collection/223929#223929 – Bill K Aug 19 '10 at 00:37
  • @Bill K - the question is more general than that. The iterator pattern is not sophisticated enough to handle arbitrary modification as the correct behaviour would differ from implementation to implementation. Eg I'm iterating a list alphabetically and a value is inserted which preceeds the current element - do I visit that next, ignore it, throw an exception, etc etc – CurtainDog Aug 19 '10 at 02:17

6 Answers6

7

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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
3

As my answer here says:

Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop

Use Iterator.remove()

Community
  • 1
  • 1
Bill K
  • 62,186
  • 18
  • 105
  • 157
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – ProgramFOX Mar 05 '14 at 17:07
1

You could use a ConcurrentHashMap

Kevin Williams
  • 2,588
  • 3
  • 24
  • 25
  • .. 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 Aug 19 '10 at 01:50
1

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
  • 3,175
  • 21
  • 17
  • 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 Aug 19 '10 at 02:57
0

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
  • 47,174
  • 11
  • 83
  • 83
  • `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 Aug 19 '10 at 00:04
0

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
  • 39,895
  • 28
  • 133
  • 186