Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Clones a map and prefixes the keys in the clone

import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main {   /**    * Clones a map and prefixes the keys in the clone, e.g.    * for mapping "JAVA_HOME" to "env.JAVA_HOME" to simulate    * the behaviour of ANT.    *    * @param source the source map    * @param prefix the prefix used for all names    * @return the clone of the source map    */   public static Map prefix(Map source, String prefix) {       if(source == null) {           return null;       }       Map result = new HashMap();       Iterator iter = source.entrySet().iterator();       while(iter.hasNext()) {           Map.Entry entry = (Map.Entry) iter.next();           Object key = entry.getKey();           Object value = entry.getValue();           result.put(prefix + '.' + key.toString(), value);       }       return result;   } }