【问题标题】:Replace String values with value in Hash Map in Java [closed]用Java中的Hashmap中的值替换字符串值[关闭]
【发布时间】:2016-10-18 04:09:03
【问题描述】:

我创建了一个哈希映射,其中包含我的键值对,用于将用户输入替换为对应于相应键的值。 对于 exp 我有多个字符串,如

 String pattern = "a+b";
 String pattern =  "C__a_plus_b+d"
 String pattern = "d+C__a_plus_b+F__c_plus_d"

我有 hashmap,其中包含类似的值

HashMap<String, String> vals = new HashMap<>();

vals.put("a", "123");
vals.put("b", "13");
vals.put("C__a_plus_b", "123");
vals.put("d", "1623");
vals.put("C__a_plus_b", "5");
vals.put("F__c_plus_d", "15");

现在我想用我的字符串中的 HashMap 中的值替换字符串,我希望我的输出像

String pattern = "a+b"; 
                123+13

String pattern =  "C__a_plus_b+d"
                    123+1623

【问题讨论】:

  • C__a_plus_b 映射到 1235。怎么回事???
  • 到目前为止你写了什么,代码方面?
  • for(HashMap.Entry val : lablemap.entrySet()) { result = operation.replace(val.getKey(), val.getValue());操作=结果; }
  • 但它不起作用,我认为特殊的 ch。没有替换
  • + 是正则表达式的特殊字符,用 "\\" 转义

标签: java string hashmap


【解决方案1】:

对于 Java 8 流,它应该类似于:

String result = String.join(
    "+",
    Arrays.asList(pattern.split("\\+"))
        .stream()
        .map((String s) -> vals.get(s))
        .collect(Collectors.toList())
);

【讨论】:

    猜你喜欢
    • 2015-04-03
    • 2021-01-06
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2022-06-10
    相关资源
    最近更新 更多