Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace all characters in a String with appropriate key value pair from a map using stream

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. 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

  1. Split string into char array and stream it
  2. Convert each char into String
  3. Use it as key in the map to get the appropriate value, if not exits mantain current
  4. Join all result to a new String
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading