Here you can find the source of substituteForTokens(String input, Map
Parameter | Description |
---|---|
input | String to process |
tokenMap | map to take keys and values from for replacing process |
invertMap | if is true then Map is inverted before replacing |
public static String substituteForTokens(String input, Map<String, String> tokenMap, boolean invertMap)
//package com.java2s; //License from project: Open Source License import java.util.HashMap; import java.util.Map; import java.util.Set; public class Main { /**//from w w w . ja v a2s . co m * Finds and replaces every key from specified Map in specified String by value from this map in brackets '${...}'. * Map can be inverted before this operation. * @param input String to process * @param tokenMap map to take keys and values from for replacing process * @param invertMap if is true then Map is inverted before replacing * @return String with every occurence of key from Map in input String replaced by its value */ public static String substituteForTokens(String input, Map<String, String> tokenMap, boolean invertMap) { if (invertMap) { tokenMap = invertStringMap(tokenMap); } input = input.replaceAll("\\$", "\\$\\$"); Set<String> keySet = tokenMap.keySet(); boolean somethingDone = false; int index; do { somethingDone = false; for (String key : keySet) { index = input.indexOf(key); if (index >= 0) { input = input.substring(0, index) + "${" + tokenMap.get(key) + "}" + input.substring(index + key.length()); somethingDone = true; break; } } } while (somethingDone); return input; } /** * Inverts Map of Strings (values become keys, keys become values). * @param input Map to invert * @return inverted Map */ public static HashMap<String, String> invertStringMap(Map<String, String> input) { HashMap<String, String> output = new HashMap<String, String>(input.size()); Set<Map.Entry<String, String>> entries = input.entrySet(); for (Map.Entry<String, String> entry : entries) { output.put(entry.getValue(), entry.getKey()); } return output; } }