'Set Map.Entry value AFTER iteration complete?

Can I save Map.Entry objects in a temporary Map and then go back and change their values AFTER iteration has completed?

For example, the following implements a sort of transaction in two steps. In step 1, a map of entries and maps of entries (so a tree of sorts) is recursively processed. Entries are processed into new values which are saved to a temporary map, keyed by the corresponding Map.Entry. If all entries are computed without Exception, step 2 is to simply iterate over the temporary map and assign the corresponding new value.

void performPerilousProcedure(Object val) throws Exception
{
    if (processing of val fails)
        throw new Exception();
}
void recurivePerilousProcedure(Map someMap, Map tmp) throws Exception
{
    Iterator<Map.Entry<String,Object>> iter1;
    iter1 = someMap.entrySet().iterator();
    while (iter1.hasNext()) {
        Map.Entry<String,Object> entry1 = iter1.next();
        Object val = entry1.getValue();
        if (val instanceof Map) {
            recursivePerilousProcedure((Map)val, tmp);
        } else {
            Object newval = performPerilousProcedure(val);
            // ok to use Map.Entry as key across iter?
            tmp.put(entry1, newval);
        }   
    }   
}
void doit(Map<String,Object> someMap) throws Exception
{
    HashMap<Map.Entry<String,Object>,Object> tmp = new HashMap();
    // Try to process map of entries and maps of entries and ma ... 
    recursivePerilousProcedure(someMap, tmp);
    // All entries success processed, now simply assign new vals
    Iterator<Map.Entry<String,Object>> iter2;
    iter2 = tmp.keySet().iterator();
    while (iter2.hasNext()) {
        Map.Entry<String,Object> entry2 = iter2.next();
        Object newval = tmp.get(entry2);
        entry2.setValue(newval); // commit new value
    }   
}

The question is:

Can the Map.Entry objects used as keys of tmp survive outside the iterations?

Provided that there are no concurrent modifications, is this a valid use of the Map interface?



Solution 1:[1]

If I'm following along, you can do something like this:

for (Entry<String, Object> entry : someMap.entrySet()) {
    Object newVal = performPerilousProcedure(entry.getValue());
    tmp.put(entry.getKey(), newVal);
}
    
someMap.putAll(tmp);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan