@Test
public void testSomething() {
    String str = "Hello ${myKey1}, welcome to Stack Overflow. Have a nice ${myKey2}";
    Map<String, String> map = new HashMap<String, String>();
    map.put("myKey1", "DD84");
    map.put("myKey2", "day");
    for (Map.Entry<String, String> entry : map.entrySet()) {
        str = str.replace("${" + entry.getKey() + "}", entry.getValue());
    }
    System.out.println(str);        
}

Output:

Hello DD84, welcome to Stack Overflow. Have a nice day

For something more complex I'd rather use OGNL.

Answer from Alfredo Osorio on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 68382743 › replace-a-map-of-values-in-string
java - Replace a map of values in string - Stack Overflow
It's relatively straightforward, if a little verbose because Java. First, create a regex expression that will accept any of the keys in the map (using Pattern.quote() to sanitize them), and then use lambda replacement to pluck the appropriate replacement from the map whenever an instance is found. The performance-intensive part is just compiling the regex in the first place; the replacement itself should make only one pass through the string.
Discussions

regex - Java Map replaceAll with multiple String matches - Stack Overflow
Does this answer your question? Java Replacing multiple different substring in a string at once (or in the most efficient way) ... replace(str, map) if we have the empty string, the result is the empty string. More on stackoverflow.com
🌐 stackoverflow.com
java - Replace string in Map key with string from Map value - Stack Overflow
To retrieve from the value minimum ... value.replaceFirst("...", "$1"); or more difficult value.indexOf("max") / substring ... Sign up to request clarification or add additional context in comments. ... First of all you should use respeated keys in a map so that's why I obtain three output instead of 4. Secondly in order to make the problem more simple you should use the same pattern: package tests; import java.util.*; public class Tester { public static void main(String[] args) { ... More on stackoverflow.com
🌐 stackoverflow.com
June 26, 2017
Replace all strings in a List that match keys in a Map
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
5
1
June 21, 2022
Replace String values with value in Hash Map in Java - Stack Overflow
I have created a hash map that contains my Key Value pairs to utilize in replacing user input with the value corresponding to the respective key. For exp i have multiple Strings like String patte... More on stackoverflow.com
🌐 stackoverflow.com
October 18, 2016
🌐
ConcretePage
concretepage.com › java › java-8 › java-map-replace
Java Map replace()
February 15, 2020 - import java.util.HashMap; import java.util.Map; public class Replace1 { public static void main(String[] args) { Map<Integer, String> studentMap = new HashMap<>(); studentMap.put(101, "Mahesh"); studentMap.put(102, "Suresh"); studentMap.put(103, "Krishna"); String oldValue = studentMap.replace(101, "Mr.
🌐
Java2s
java2s.com › example › java-utility-method › map-replace › replace-string-text-map-string-pairs-485e9.html
Java Map Replace replace(String text, Map<String, ?> pairs)
*/ import java.util.Map; public class Main { public static String replace(String text, Map<String, ?> pairs) { StringBuilder result = new StringBuilder(text); for (String old : pairs.keySet()) { if (old != null) { if (!old.equals("")) { replaceString(result, old, pairs.get(old)); } } } return result.toString(); } public static StringBuilder replaceString(StringBuilder source, String oldFragment, Object newObject) { if (oldFragment != null) { int lengthOld = oldFragment.length(); String newFragment; if (newObject != null) { if (newObject instanceof Integer) { newFragment = ((Integer) newObject)
🌐
Programiz
programiz.com › java-programming › library › hashmap › replace
Java HashMap replace()
The replace() method can take 3 parameters. ... the previous value associated with the specified key, if the optional parameter oldValue is not present · true, if the optional parameter oldValue is present · Note: The method returns null, if either the specified key is mapped to a null value or the key is not present on the hashmap. import java.util.HashMap; class Main { public static void main(String[] args) { // create an HashMap HashMap<Integer, String> languages = new HashMap<>(); // add entries to HashMap languages.put(1, "Python"); languages.put(2, "English"); languages.put(3, "JavaScript"); System.out.println("HashMap: " + languages); // replace mapping for key 2 String value = languages.replace(2, "Java"); System.out.println("Replaced Value: " + value); System.out.println("Updated HashMap: " + languages); } }
Top answer
1 of 3
1

I'd do it thus:

replace(str, map)
    if we have the empty string, the result is the empty string.
    if the string starts with one of the keys from the map:
        the result is the replacement associated with that key + replace(str', map)
             where str' is the substring of str after the key
    otherwise the result is the first character of str + replace(str', map)
             where str' is the substring of str without the first character

Note that, though formulated recursively, it can (and should, due to Javas notorious small stack space) be implemented as a loop and write the first part of the result (i.e. the replacement string or the first character) to a stringbuilder.

If you have a key in the map that is a prefix of some other key (i.e. "key", "keys") you may need to try the keys in decreasing length.

Note further, that a faster algorithm could be devised that uses Tries instead of HasMaps. This would also be a remedy for the ambiguous key problem.

Here is an outline (not tested):

public static String replace(String it, Map<String, String> map) {
    StringBuilder sb = new StringBuilder();
    List<String> keys = map.keySet();      // TODO: sort by decreasing length!!
    next: while (it.length() > 0) {
        for (String k : keys) {
            if (it.startsWith(k)) {
                // we have a match!
                sb.append(map.get(k));
                it = it.substring(k.length(), it.length());
                continue next;
            }
        }
        // no match, advance one character
        sb.append(it.charAt(0));
        it = it.substring(1, it.length());
    }
    return sb.toString();
}
2 of 3
1

My approach would be the following. There are probably faster solutions, but you can take it a step further if you like the idea.

public String mapReplaceAll5(String str, Map<String, String> replacements) {
    Map<String, String> origToMarker = new HashMap<String, String>();
    Map<String, String> markerToRepl = new HashMap<String, String>();
    char c = 32000;
    for(Entry<String, String> e : replacements.entrySet()) {
        origToMarker.put(e.getKey(), String.valueOf(c));
        markerToRepl.put(String.valueOf(c--), e.getValue());
    }
    for (Map.Entry<String, String> entry : origToMarker.entrySet()) {
        str = str.replaceAll(entry.getKey(), entry.getValue());
    }
    for (Map.Entry<String, String> entry : markerToRepl.entrySet()) {
        str = str.replaceAll(entry.getKey(), entry.getValue());
    }

    return str;
}
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
GeeksforGeeks
geeksforgeeks.org › java › hashmap-replaceallbifunction-method-in-java-with-examples
HashMap replaceAll(BiFunction) method in Java with Examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate // replaceAll(BiFunction) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // create a HashMap having // record of the year of birth HashMap<String, Integer> map1 = new HashMap<>(); map1.put("Tushar", 2000); map1.put("Anushka", 2001); map1.put("Sanskriti", 2003); map1.put("Anuj", 2002); // print map details System.out.println("HashMap1: " + map1.toString()); // replace yearOfBirth with current age // using replaceAll method map1.replaceAll((key, yearOfBirth) -> 2019 - yearOfBirth); // print new mapping System.out.println("New HashMap: " + map1); } }
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 44757054 › replace-string-in-map-key-with-string-from-map-value
java - Replace string in Map key with string from Map value - Stack Overflow
June 26, 2017 - To retrieve from the value minimum and maximum, one could use a regular expression pattern matching: value.replaceFirst("...", "$1"); or more difficult value.indexOf("max") / substring ... Sign up to request clarification or add additional context in comments. ... First of all you should use respeated keys in a map so that's why I obtain three output instead of 4. Secondly in order to make the problem more simple you should use the same pattern: package tests; import java.util.*; public class Tester { public static void main(String[] args) { getFinal(initial(data)); } public static Map<String,
🌐
Coderanch
coderanch.com › t › 615192 › java › Regex-replaceAll-HashMap-Code
Regex,replaceAll with HashMap (Code Issue) (Java in General forum at Coderanch)
Tony Docherty wrote:That will look for and replace all occurrences of the hash key not preceded by '!' and replace them with the hash value - is that what you wanted to do? well i have a what i want to do is i am replace #template in my string to some value which is in hashmap value for Instance in the scenario i have key = "#template", value "emailTemplate" i want to replace it in string using hashmap.
🌐
Reddit
reddit.com › r/javahelp › replace all strings in a list that match keys in a map
r/javahelp on Reddit: Replace all strings in a List that match keys in a Map
June 21, 2022 -

I apparently suck at Googling, lol, because I can't find this. I have a Map<String, String> of nicknames. So it will have like "William", "Will" and "James", "Jim" etc. Problem is, I need to examine a List<String> and swap out any that match but it could be any case. I was hoping there is a way to do some fancy stream type of thing, because what I'm doing now works but it doesn't feel very efficient:

for (Map.Entry<String, String> nick : nicks.entrySet()) {
  if (!segments.stream().anyMatch(nick.getKey()::equalsIgnoreCase)) continue;
  
  for (int x=0; x<segments.size(); x++) {
    if (!segments.get(x).equalsIgnoreCase(nick.getKey())) continue;
    
    segments.set(x, nick.getValue());
  }
}

I read about how to easily check the List to see if any strings exist in it, so I can at least avoid having to iterate each element of the list to check for that but I was hoping there was some fancy way to also pull off the replace w/o having to iterate...?

Top answer
1 of 5
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 5
1
Iterate on the list and lookup the elements in the map. Will be much more efficient. Also see if you can create a new list with the results, instead of changing the original.
🌐
Dotnetcodr
dotnetcodr.com › 2015 › 02 › 15 › replacing-a-value-in-a-map-in-java-8
Replacing a value in a Map in Java 8 | Exercises in .NET with Andras Nemes
February 24, 2015 - ... Map<String, String> sizes = new HashMap<>(); sizes.put("XS", "Extra small"); sizes.put("S", "Small"); sizes.put("M", "Medium"); sizes.put("L", "Large"); sizes.put("XL", "Extra large"); sizes.put("XXL", "Extra extra large");
🌐
Devcubicle
devcubicle.com › hashmap-replace-method-in-java
HashMap replace() Method in Java - DevCubicle By Cloud Tech
October 1, 2021 - It returns true on successful replacement, otherwise, it returns false. ... import java.util.HashMap; import java.util.Map; public class HashMapReplaceExample { public static void main(String[] args) { Map map = new HashMap (); map.put(101, "John"); map.put(102, "Adam"); map.put(103, "Ricky"); map.put(104, "Chris"); System.out.println("Elements: " + map); // replace John with Shaun // replace method returns the old value String oldValue = map.replace(101, "Shuan"); System.out.println("Replaced John by Shaun for key 101: " + oldValue); System.out.println("Modified elements: " + map); // returns null if map // does not contain specified key System.out.println("No key is present for 108: " + map.replace(108, "Gary")); } }
🌐
Java Tutorial HQ
javatutorialhq.com › java tutorial › java.util › hashmap › replace() method example
Java HashMap replace() method example
September 30, 2019 - package com.javatutorialhq.java.examples; import static java.lang.System.*; import java.util.HashMap; /* * This example source code demonstrates the use of * replace(K key, V value) method of HashMap class */ public class HashMapReplaceExample { public static void main(String[] args) throws InterruptedException { // get the HashMap object from the method init() HashMap<Integer, String> map = init(); // replace the id 18975 with a new student String result = map.replace(73654, "Darwin Bocalbos"); if (result != null) { out.println("Student " + result + " has been replaced on the student database
🌐
W3Schools
w3schools.com › java › ref_hashmap_replace.asp
Java HashMap replace() Method
The replace() method writes a new value to an existing entry in the map. The entry can be specified by its key, or by both its key and value.
🌐
Coderanch
coderanch.com › t › 404815 › java › String-replace-HashMap
String replace from HashMap (Beginning Java forum at Coderanch)
September 16, 2006 - programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... I know its an old and tried question but i do not understand why this code does not work. public class testreplace { public static void main(String args[]){ String key="$re$"; String value = "rec"; String message = "me $re$ now"; message = message.replaceAll(key,value); System.out.println(newm); } } Iam reading the key and value from a HashMap and i need to replace any occurance of a key with the value in the String.
🌐
Stack Overflow
stackoverflow.com › questions › 60983887 › how-to-replace-some-words-with-given-replacement-map-in-java
How to replace some words with given replacement map in java? - Stack Overflow
... String str = "Don't trouble trouble until trouble troubles you"; Map<String,String> replacementMap = new HashMap<String, String>(){{put("trouble","replaceStr");}}; for (Map.Entry<String, String> entry : replacementMap.entrySet()) { ...
🌐
JavaGoal
javagoal.com › home › how to replace the value by hashmap replace() method
java hashmap replace and replace hashmap - JavaGoal
September 10, 2020 - If oldValue doesn’t match with the associated key, then it does not replace the value. Its return type is boolean. Where Key is the key with which the specified value(V) is to be associated with HashMap. oldValue is the value to be associated with the specified key(K) in HashMap. newValue is the value that will be associate with the specified key(K) in HashMap. import java.util.HashMap; public class ExampleOfHashMap { public static void main(String[] args) { HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); // Adding objects in HashMap hashMap.put(1, "JavaGoal.com"); hashMap.put(2, "Learning"); hashMap.put(3, "Website"); // Before replacing entry System.out.println("Before replacing HashMap: "+ hashMap); hashMap.replace(2, "Learning", "A Learning"); // After replacing entry System.out.println("After replacing HashMap: "+ hashMap); } }
🌐
Medium
medium.com › @AlexanderObregon › javas-map-replace-method-explained-150962a66f80
Java’s Map.replace() Method Explained | Medium
December 19, 2024 - V replace(K key, V value); For example, if you have a map storing user preferences and want to update a specific setting without adding new keys, this method updates only existing keys.