Search code examples
javacollectionshashmapiteratorconcurrentmodification

concurrent modification exception while iterating list map string object and edit key


I'm putting in a List<Map<String, Object>> the result of a query along with the column names. Sometimes column names are like TableAlias.ColumnName, in that case I want to change it to just ColumnName and remove TableAlias. for that I have below code:

queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);

for (Map<String, Object> map : queryResult) {
    for (Map.Entry<String, Object> entry : map.entrySet()) {            
        String[] keyData = entry.getKey().split("\\.");
        if (keyData.length > 0) {
            Object obj = map.remove(entry.getKey());
            map.put(keyData[1], obj);
        }                   
    }
}

That is giving me concurrent modification exception so I was trying with an iterator like below:

for (Map<String, Object> map : queryResult) {
    for(Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext(); ) {
        Map.Entry<String, Object> entry = it.next();
        String[] keyData = entry.getKey().split("\\.");
        if (keyData.length > 0) {
            it.remove();                        
        }
    }
}

But not sure how to add the item back with the new key.

Any suggestions please?


Solution

  • I would iterate over the original map and fill another map with the updated keys.

    queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);
    
    Map<String, Object> newMap = new HashMap<>();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
       String[] keyData = entry.getKey().split("\\.");
       if (keyData.length > 1) {
           newMap.put(keyData[1], entry.getValue());
       } else {
           newMap.put(entry.getKey(), entry.getValue());
       }
    }