Java 8将HashMap上的Map减少为lambda

Wil*_*ina 8 java string lambda hashmap java-8

我有一个String并且想要替换其中的一些单词.我有一个HashMap关键是要替换的占位符和替换它的单词的值.这是我的老派代码:

  private String replace(String text, Map<String, String> map) {
    for (Entry<String, String> entry : map.entrySet()) {
      text = text.replaceAll(entry.getKey(), entry.getValue());
    }
    return text;
  }
Run Code Online (Sandbox Code Playgroud)

有没有办法将此代码编写为lambda表达式?

我尝试entrySet().stream().map(...).reduce(...).apply(...);但无法使其工作.

提前致谢.

Hol*_*ger 8

我不认为您应该尝试找到更简单或更简短的解决方案,而是考虑您的方法的语义和效率.

您正在迭代可能没有指定迭代顺序的地图(例如HashMap)并执行一个接一个的替换,使用替换的结果作为输入到由于先前应用替换或替换替换中的内容而导致的下一个可能缺失的匹配.

即使我们假设您正在传递其键和值没有干扰的地图,这种方法效率也很低.进一步注意,replaceAll将参数解释为正则表达式.

如果我们假设没有正则表达式,我们可以通过按长度排序来清除密钥之间的歧义,以便首先尝试更长的密钥.然后,执行单个替换操作的解决方案可能如下所示:

private static String replace(String text, Map<String, String> map) {
    if(map.isEmpty()) return text;
    String pattern = map.keySet().stream()
        .sorted(Comparator.comparingInt(String::length).reversed())
        .map(Pattern::quote)
        .collect(Collectors.joining("|"));
    Matcher m = Pattern.compile(pattern).matcher(text);
    if(!m.find()) return text;
    StringBuffer sb = new StringBuffer();
    do m.appendReplacement(sb, Matcher.quoteReplacement(map.get(m.group())));
       while(m.find());
    return m.appendTail(sb).toString();
}
Run Code Online (Sandbox Code Playgroud)

从Java 9开始,您可以使用StringBuilder而不是在StringBuffer这里

如果你测试它

Map<String, String> map = new HashMap<>();
map.put("f", "F");
map.put("foo", "bar");
map.put("b", "B");
System.out.println(replace("foo, bar, baz", map));
Run Code Online (Sandbox Code Playgroud)

你会得到

bar, Bar, Baz
Run Code Online (Sandbox Code Playgroud)

证明替换foo优先于替换,f并且b替换bar内部不替换.

如果你再次替换替换中的匹配,那将是另一回事.在这种情况下,您需要一种机制来控制订单或实现重复替换,只有在没有匹配时才会返回.当然,后者需要小心提供最终会收敛到结果的替换.

例如

private static String replaceRepeatedly(String text, Map<String, String> map) {
    if(map.isEmpty()) return text;
    String pattern = map.keySet().stream()
        .sorted(Comparator.comparingInt(String::length).reversed())
        .map(Pattern::quote)
        .collect(Collectors.joining("|"));
    Matcher m = Pattern.compile(pattern).matcher(text);
    if(!m.find()) return text;
    StringBuffer sb;
    do {
        sb = new StringBuffer();
        do m.appendReplacement(sb, Matcher.quoteReplacement(map.get(m.group())));
           while(m.find());
        m.appendTail(sb);
    } while(m.reset(sb).find());
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
Map<String, String> map = new HashMap<>();
map.put("a", "e1");
map.put("e", "o2");
map.put("o", "x3");
System.out.println(replaceRepeatedly("foo, bar, baz", map));
Run Code Online (Sandbox Code Playgroud)
fx3x3, bx321r, bx321z
Run Code Online (Sandbox Code Playgroud)