/** * Walk through the map and rename all instances of oldKey to newKey. */ @VisibleForTesting protected static void renamePrefixKeys(Map<String, Collection<String>> image, String oldKey, String newKey) { // The trick is that we can't just iterate through the map, remove old values and // insert new values. While we can remove old values with iterators, // we can't insert new ones while we walk. So we collect the keys to be added in // a new map and merge them in the end. Map<String, Set<String>> replacement = new HashMap<>(); for (Iterator<Map.Entry<String, Collection<String>>> it = image.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String, Collection<String>> entry = it.next(); String key = entry.getKey(); if (key.startsWith(oldKey)) { String updatedKey = key.replaceAll("^" + oldKey + "(.*)", newKey + "$1"); if (!image.containsKey(updatedKey)) { LOGGER.debug("Rename {} to {}", key, updatedKey); replacement.put(updatedKey, (Set<String>) entry.getValue()); it.remove(); } else { LOGGER.warn("skipping key {} - already present", updatedKey); } } } mergeMaps(image, replacement); }