Re: [Map]modifying a map through an iteration



In article <490d94b2$0$28669$7a628cd7@xxxxxxxxxxxxxxxxxxxxx>,
Daniel Moyne <daniel.moyne@xxxxxxx> wrote:

[...] Can we say?

(1) that within the loop modifying values attached to a key is not a problem
because the iteration is done via the key, this on keys already processed or
to be processed,

Generally, this is correct, but not because of when the key is returned
by the (hidden) iterator. It's because the List returned by
entry.getValue() is being modified, and the Map itself is unchanged.

(2) that modifications applied to entries are equivalent to modifications
applied to the map (within the loop) meaning that if for some reasons in that
very loop I have to re-loop through my map I am handling here an updated
object ?),

Cephalgia exception.

(3) that removing a key may be problematic except the currently processed one
with something like :
allNamePartitions.remove(entry.getKey();
as entry.remove does not exist ; this of course if there is full coherence
between the map and the generated entry set (?),

If you try to remove a value from a Map while iterating you'll get
ConcurrentModificationException (note that for-each hides the iterator,
but it's still there):

<http://java.sun.com/javase/6/docs/api/java/util/HashMap.html>

(4) that otherwise removing a key backwards or forwards (using for example
another nested loop) may not be possible.

Of course as suggested when removing a key I can break the process and
rebuild the map by re-entring the loop with something like this if possible
(is it possible to remove a key in suche a loop ?) :
[...]
As far as keys are concerned this map process could be applied to a list or
items when through iteration you want to remove an item other than the one
currently processed.

But this if workable is particularly unefficient as I have to reprocess keys
again and again each time until I reach the point where I had the last break.

Instead of trying to remove Map values while iterating, just remember
which one(s) are slated for annihilation:

<code>
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author John B. Matthews
*/
public class MapTest {

private static final Map<String, List<String>> map =
new HashMap<String, List<String>>();

public static void main(String[] args) {
List<String> list = new ArrayList<String>(
Arrays.asList("Alpha", "Beta", "Gamma"));
map.put("Ordinals", list);

list = new ArrayList<String>(
Arrays.asList("Aleph", "Beth", "Gimel"));
map.put("Cardinals", list);

list = new ArrayList<String>(
Arrays.asList("Alpher", "Bethe", "Gammow"));
map.put("Physicists", list);

List<String> mapValuesToRemove = new ArrayList<String>();
printMap(map);
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if (entry.getValue().contains("Gamma")) {
entry.getValue().remove("Gamma"); // OK
// throws ConcurrentModificationException
// map.remove(entry.getKey());
// if it's time to go?
mapValuesToRemove.add(entry.getKey());
}
}
for (String s : mapValuesToRemove) map.remove(s);
printMap(map);
}

private static void printMap(Map<String, List<String>> map) {
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey()
+ " " + entry.getValue());
}
}
}
</code>

--
John B. Matthews
trashgod at gmail dot com
http://home.roadrunner.com/~jbmatthews/
.



Relevant Pages

  • Re: [Map]modifying a map through an iteration
    ... that within the loop modifying values attached to a key is not a problem because the iteration is done via the key, this on keys already processed or to be processed, ... It's because the List returned by entry.getValueis being modified, and the Map itself is unchanged. ... items when through iteration you want to remove an item other than the one currently processed. ...
    (comp.lang.java.help)
  • Yow! LOOP macros are LOOPY!
    ... By relying entirely on procedure calls to express iteration, ... to but cleaner than C's FOR loop. ... other macros going around at the time other than MacLisp's ... (bind (vi (vector-ref v i))) ...
    (comp.lang.scheme)
  • Re: Polling, Interrupts, DMA, Synchronous, Asynchronous I/O Definitions
    ... the terminology is less useful than it might be. ... though a "message loop" could arguably be claimed to be ... considering in a particular iteration but what is true for _ALL_ ... watching the "polling" version eating up every single CPU cycle ...
    (alt.lang.asm)
  • Re: Histogram of character frequencies
    ... generated object code may simply be a loop in which elements are ... believe any C compiler anywhere would reject it. ... On the first iteration of the loop you test the end of file indicator ...
    (comp.lang.c)
  • Re: Random number help
    ... is used to generate cooccurance matrix for each iteration of for loop. ... disp('the sample co-occurance matrix is as follows');% GIVING SAME ...
    (comp.soft-sys.matlab)