How do I use replace() and replaceAll() methods of Map?

In Java, the Map interface provides the methods replace() and replaceAll(), which are used to replace existing entries in the map.

Replace:

replace(K key, V value) is a method that replaces the entry for the specified key only if it is currently mapped to some value. It returns the old value associated with the specified key or null if the key is not in the map.

Here is a simple usage of the replace() method:

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapReplaceExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "v1");
        map.replace("key1", "value1");

        // Output: New value of key1: value1
        System.out.println("New value of key1: " + map.get("key1"));
    }
}

Output:

New value of key1: value1

replace(K key, V oldValue, V newValue) replaces the entry for the specified key only if currently mapped to the specified value. This variant of replace() method provides additional check for existing value, which can prevent data corruption in concurrent environment without additional synchronization.

ReplaceAll:

replaceAll(BiFunction<? super K,? super V,? extends V> function) is a method that replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

Here is a simple usage of the replaceAll() method:

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapReplaceAllExample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "v1");
        map.put("key2", "v2");

        map.replaceAll((k, v) -> v.toUpperCase());

        // Output: {key1=V1, key2=V2}
        System.out.println(map);
    }
}

Output:

{key1=V1, key2=V2}

In this example, the replaceAll() method is used to replace every value in the map with its uppercase version. The provided function should be non-interfering and stateless.

The benefits of using replace() and replaceAll() methods are:

  • They are more concise and expressive.
  • They can improve code readability and maintainability.
  • They are beneficial while working in a multi-thread environment because they provide additional safety without additional synchronization.

How to remove non ASCII characters from a string?

The code snippet below remove the characters from a string that is not inside the range of x20 and x7E ASCII code. The regex below strips non-printable and control characters. But it also keeps the linefeed character n (x0A) and the carriage return r (x0D) characters.

package org.kodejava.regex;

public class ReplaceNonAscii {
    public static void main(String[] args) {
        String str = "Thè quïck brøwn føx jumps over the lãzy dôg.";
        System.out.println("str = " + str);

        // Replace all non ascii chars in the string.
        str = str.replaceAll("[^\\x0A\\x0D\\x20-\\x7E]", "");
        System.out.println("str = " + str);
    }
}

Snippet output:

str = Thè quïck brøwn føx jumps over the lãzy dôg.
str = Th quck brwn fx jumps over the lzy dg.

How do I replace text in the JTextArea?

In this example you’ll see how to use the replaceRange(String str, int start, int end) method to replace a string in the JTextArea from the start position to the end position with the specified string.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;

public class TextAreaReplaceText extends JPanel {
    public TextAreaReplaceText() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TextAreaReplaceText();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTextArea Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TextAreaReplaceText::showFrame);
    }

    private void initializeUI() {
        String text = "The quick white fox jumps over the sleepy dog.";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        textArea.replaceRange("brown", 10, 15);
        textArea.replaceRange("lazy", 35, 41);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The screenshot of the code snippet above is:

JTextArea Replace Text Demo

How do I append and replace content of a StringBuffer?

A StringBuffer is like a String, but can be modified. StringBuffer are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

As of release JDK 1.5, this class has been supplemented with an equivalent class designed for use by a single thread, the StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all the operations, but it is faster, as it performs no synchronization.

package org.kodejava.lang;

public class StringBufferAppendReplace {
    public static void main(String[] args) {
        StringBuffer quote = new StringBuffer("an apple ");
        char a = 'a';
        String day = " day";
        StringBuffer sentences = new StringBuffer(" keep the doctor away");

        // Append a character into StringBuffer
        quote.append(a);
        System.out.println("quote = " + quote);

        // Append a string into StringBuffer
        quote.append(day);
        System.out.println("quote = " + quote);

        // Append another StringBuffer
        quote.append(sentences);
        System.out.println("quote = " + quote);

        // Replace a sub string from StringBuffer starting
        // from index = 3 to index = 8
        quote.replace(3, 8, "orange");
        System.out.println("quote = " + quote);
    }
}

Here is our program output:

quote = an apple a
quote = an apple a day
quote = an apple a day keep the doctor away
quote = an orange a day keep the doctor away

How do I find and replace string?

The code below demonstrates the use Matcher.appendReplacement() and Matcher.appendTail() methods to create a program to find and replace a sub string within a string.

Another solution that can be used to search and replace a string can be found on the following example: How do I create a string search and replace using regex?.

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppendReplacementExample {
    public static void main(String[] args) {
        // Create a Pattern instance
        Pattern pattern = Pattern.compile("[Pp]en");

        // Create matcher object
        String input = "Please use your Pen to answer the question, " +
                "black pen is preferred.";
        Matcher matcher = pattern.matcher(input);
        StringBuilder builder = new StringBuilder();

        // Find and replace the text that match the pattern
        while (matcher.find()) {
            matcher.appendReplacement(builder, "pencil");
        }

        // This method reads characters from the input sequence, starting
        // at the beginning position, and appends them to the given string
        // builder. It is intended to be invoked after one or more
        // invocations of the appendReplacement method in order to copy
        // the remainder of the input sequence.
        matcher.appendTail(builder);

        System.out.println("Input : " + input);
        System.out.println("Output: " + builder);
    }
}

Here is the result of the above code:

Input : Please use your Pen to answer the question, black pen is preferred.
Output: Please use your pencil to answer the question, black pencil is preferred.