You could write a text replacer that replaces every character by reducing the string according to each entry in the Map
. You can optimize the string replacement by manipulating a StringBuilder
object instead of a plain String
.
import java.util.*;
import java.util.stream.Collectors;
public class TextReplacer {
private static final Map<String, String> replacements;
private static final List<String> phrases;
static {
phrases = List.of("Hello World", "Do you like peppers?");
replacements = new HashMap<String, String>() {{
put("r", "m");
put("e", "i");
put("s", "n");
put("p", "u");
}};
}
public static void main(String[] args) {
replaceAll(phrases, replacements).stream().forEach(System.out::println);
replaceAllOptimized(phrases, replacements).stream().forEach(System.out::println);
}
public static String replace(String phrase, Map<String, String> replacements) {
return replacements.entrySet().stream().reduce(phrase.toLowerCase(), (s, e) -> s.replace(e.getKey(), e.getValue()), (s1, s2) -> null);
}
public static List<String> replaceAll(List<String> phrases, Map<String, String> replacements) {
return phrases.stream().map(s -> replace(s, replacements)).collect(Collectors.toList());
}
public static String replaceOptimized(String phrase, Map<String, String> replacements) {
return replacements.entrySet().stream().reduce(new StringBuilder(phrase.toLowerCase()), (s, e) -> replaceAll(s, e.getKey(), e.getValue()), (s1, s2) -> null).toString();
}
public static List<String> replaceAllOptimized(List<String> phrases, Map<String, String> replacements) {
return phrases.stream().map(s -> replaceOptimized(s, replacements)).collect(Collectors.toList());
}
public static StringBuilder replaceAll(StringBuilder builder, String from, String to) {
int index = builder.indexOf(from);
while (index != -1) {
builder.replace(index, index + from.length(), to);
index += to.length();
index = builder.indexOf(from, index);
}
return builder;
}
}
Output
hillo womld
do you liki uiuuimn?
hillo womld
do you liki uiuuimn?