I have a map of String entries.
Map<String, String> forConversion = Map.ofEntries(
Map.entry("$","s"),
Map.entry("§ ","ss"),
Map.entry("Đ ","d"),
,...);
Input String
String input= "$ab§d";
//shoud be converted to
//"sabssd"
How I can do this using java streams. Think it is possible and easy. 🙂
>Solution :
here it is
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Map<String, String> forConversion = Map.of(
"$", "s",
"§", "ss",
"Đ", "d"
// add more mappings as needed
);
String input = "$ab§d";
String output = input.chars()
.mapToObj(c -> String.valueOf((char) c))
.map(s -> forConversion.getOrDefault(s, s))
.collect(Collectors.joining());
System.out.println(output); // prints "sabssd"
}
}
Logic steps are simple:
- Split string into char array and stream it
- Convert each char into String
- Use it as key in the map to get the appropriate value, if not exits mantain current
- Join all result to a new String