简体   繁体   中英

How to convert mixed map string back to mixed map in Java

I have a mixed map like: private Map<Integer, Map<Character, Float>> probabilities = new HashMap<>();

And the output for that as string is: this.probabilities.toString() => {0={a=0.5}, 1={s=0.75}, 2={ =1.0}}

So is there I way to convert this output to mixed map as before?

Keep in mind that I can have any type of Character like "}" that could end up looking like:

{0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={ =0.875}, 5={}=1.0}}

Here is a method for parsing that string back into your nested map.

static Map<Integer, Map<Character, Float>> parse(String input) {
    if (! input.startsWith("{") || ! input.endsWith("}"))
        throw new IllegalArgumentException("Invalid input (missing surrounding '{}'): " + input);
    Map<Integer, Map<Character, Float>> output = new LinkedHashMap<>();

    Matcher m = Pattern.compile("\\G(\\d+)=\\{(.)=([0-9.]+)\\}(?:, |$)")
            .matcher(input).region(1, input.length() - 1);
    int end = 1;
    while (m.find()) {
        output.computeIfAbsent(Integer.valueOf(m.group(1)), k -> new LinkedHashMap<>())
                .put(m.group(2).charAt(0), Float.valueOf(m.group(3)));
        end = m.end();
    }
    if (end != input.length() - 1)
        throw new IllegalArgumentException("Invalid input at: " + input.substring(end));
    return output;
}

Test

Map<Integer, Map<Character, Float>> probabilities = new TreeMap<>(Map.of(
        0, Map.of('a', 0.25f),
        1, Map.of('"', 0.5f),
        2, Map.of('s', 0.625f),
        3, Map.of('{', 0.75f),
        4, Map.of('�', 0.875f),
        5, Map.of('}', 1.0f)
));
System.out.println("probabilities = " + probabilities);

String input = "{0={a=0.25}, 1={\"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}";
System.out.println("input         = " + input);

Map<Integer, Map<Character, Float>> output = parse(input);
System.out.println("output        = " + output);

Output

probabilities = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
input         = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
output        = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM