Java Guava: Remove and put back elements from Multimap while iterating -
what i'm trying achieve following: while iterating on both keys , values of multimap<k,v>, want remove and put back elements list. approach i've tried ends in concurrentmodificationexception. remove-and-put-back-approach required implement backtrack search (see here: implementing backtrack search heuristic? )
this may like:
multimap<k,v> multimap = hashmultimap.create(); iterator keyiterator = multimap.keyset().iterator(); while(keyiterator.hasnext()) { k key = keyiterator.next(); collection values = multimap.get(key); iterator valueiterator = values.iterator(); while(valueiterator.hasnext()) { v myvalue = valueiterator.next(); if(special) { valueiterator.remove(); keyiterator.remove(); // recursion // put collection key without myvalue <-- how? } } }
one solution iterate on copy of keyset, e.g.
k[] array = multimap.keyset().toarray(new k[0]); for(int = 0; < array.length; i++) { k key = array[i]; ... } changes underlying map won't reflected in array, won't concurrentmodificationexception if use iterator on it, , won't weird behavior if iterate on loop.
another option copy-paste source code multimap new collection mymultimap, except you'd replace top-level hashmap concurrenthashmap - latter's iterators won't throw concurrentmodificationexceptions.
another option coalesce 2 loops 1 loop, , iterate directly on map's entries - way you'll have 1 iterator, won't have problem of 1 iterator causing concurrentmodificationexceptions in second iterator.
Comments
Post a Comment