Java Map Replace replaceFromMap(String string, Map replacements)

Here you can find the source of replaceFromMap(String string, Map replacements)

Description

Replaces all occurrences of keys of the given map in the given string with the associated value in that map.

License

Apache License

Declaration

public static String replaceFromMap(String string, Map<String, String> replacements) 

Method Source Code

//package com.java2s;
/*-------------------------------------------------------------------------+
|                                                                          |
| Copyright 2005-2011 The ConQAT Project                                   |
|                                                                          |
| Licensed under the Apache License, Version 2.0 (the "License");          |
| you may not use this file except in compliance with the License.         |
| You may obtain a copy of the License at                                  |
|                                                                          |
|    http://www.apache.org/licenses/LICENSE-2.0                            |
|                                                                          |
| Unless required by applicable law or agreed to in writing, software      |
| distributed under the License is distributed on an "AS IS" BASIS,        |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| See the License for the specific language governing permissions and      |
| limitations under the License.                                           |
+-------------------------------------------------------------------------*/

import java.util.Iterator;

import java.util.Map;
import java.util.Map.Entry;

public class Main {
    /** Line break. */
    public static final String CR = System.getProperty("line.separator");
    /** The empty string. */
    public static final String EMPTY_STRING = "";

    /**//from  ww  w  . j  a va  2s . c o m
     * Replaces all occurrences of keys of the given map in the given string
     * with the associated value in that map. The given map may be
     * <code>null</code>, in which case the original string is returned
     * unchanged.
     * 
     * This method is semantically the same as calling
     * {@link String#replace(CharSequence, CharSequence)} for each of the
     * entries in the map, but may be significantly faster for many replacements
     * performed on a short string, since
     * {@link String#replace(CharSequence, CharSequence)} uses regular
     * expressions internally and results in many String object allocations when
     * applied iteratively.
     * 
     * The order in which replacements are applied depends on the order of the
     * map's entry set.
     */
    public static String replaceFromMap(String string, Map<String, String> replacements) {
        if (replacements == null) {
            return string;
        }

        StringBuilder sb = new StringBuilder(string);
        for (Entry<String, String> entry : replacements.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();

            int start = sb.indexOf(key, 0);
            while (start > -1) {
                int end = start + key.length();
                int nextSearchStart = start + value.length();
                sb.replace(start, end, value);
                start = sb.indexOf(key, nextSearchStart);
            }
        }
        return sb.toString();
    }

    /**
     * Searches the elements of a string array for a string. Strings are
     * trimmed.
     * 
     * @param array
     *            the array to search
     * @param string
     *            the search string
     * @return the index of the element where the string was found or
     *         <code>-1</code> if string wasn't found.
     */
    public static int indexOf(String[] array, String string) {
        for (int i = 0; i < array.length; i++) {
            if (array[i].trim().equals(string.trim())) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Create string representation of a map.
     */
    public static String toString(Map<?, ?> map) {
        return toString(map, EMPTY_STRING);
    }

    /**
     * Create string representation of a map.
     * 
     * @param map
     *            the map
     * @param indent
     *            a line indent
     */
    public static String toString(Map<?, ?> map, String indent) {
        StringBuilder result = new StringBuilder();
        Iterator<?> keyIterator = map.keySet().iterator();

        while (keyIterator.hasNext()) {
            result.append(indent);
            Object key = keyIterator.next();
            result.append(key);
            result.append(" = ");
            result.append(map.get(key));
            if (keyIterator.hasNext()) {
                result.append(CR);
            }
        }

        return result.toString();
    }
}

Related

  1. replaceCharacters(String sequence, Map map, boolean reverse)
  2. replaceCharactersInArray(char[] characters, Map replacements)
  3. replaceElements(Map destinationMap, Map sourceMap)
  4. replaceEntities(final Map replacements, final String xml)
  5. replaceFromMap(final String string, final Map replacements)
  6. replaceGlobalTokensFromMap(Map dataMap, String message)
  7. replaceInvalid(String uri, Map reps)
  8. replaceKey(final Map map, final TKey oldkey, final TKey newkey)
  9. replaceKey(Map map, K oldKey, K newKey)