【问题标题】:Java 8 Map Reduce on HashMap as lambdaHashMap 上的 Java 8 Map Reduce 作为 lambda
【发布时间】:2018-11-16 21:18:36
【问题描述】:

我有一个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;
  }

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

我尝试了entrySet().stream().map(...).reduce(...).apply(...);,但无法成功。

提前致谢。

【问题讨论】:

  • 要厌倦的一件事是包含在较大占位符中的短占位符。确保占位符按长度排序,最长在前。

标签: java string lambda java-8 hashmap


【解决方案1】:

您可以按如下方式使用每个循环:

  private String replace(String text, Map<String, String> map) {
      final StringBuilder sb = new StringBuilder(text);
      map.forEach((k,v)->replaceAll(sb, k, v));
      return sb.toString();
  }

替换所有方法可以定义为:

public static void replaceAll(StringBuilder builder, String from, String to){
    int index = builder.indexOf(from);
    while (index != -1)
    {
        builder.replace(index, index + from.length(), to);
        index += to.length(); // Move to the end of the replacement
        index = builder.indexOf(from, index);
    }
}

如果您使用多线程,也可以使用StringBuffer

【讨论】:

  • "text" 是一个不可变的字符串,所以它必须再次保存在变量 "text" 中,但这不可能,因为 text 不是最终的。
  • 查看编辑。您可以使用可变的 StringBuffer。
  • @Kaushal28 StringBuffer 没有replaceAll 方法
【解决方案2】:

@RavindraRanwala 的代码几乎没有改进。

    String replacement = Stream.of(text.split("\\b"))
            .map(token -> map.getOrDefault(token, token))
            .collect(Collectors.joining(""));

1) 使用 Java 8 中的Map.getOrDefault

2) 用“\b”分割以支持任何单词的分隔符,而不仅仅是空格字符

【讨论】:

  • 还有Pattern.compile("\\b").splitAsStream(text)——这样预编译的Pattern可以被重用,并且避免了数组的创建
【解决方案3】:

出于实际目的,您的非流代码就可以了。作为一个有趣的练习,您可以将每个映射表示为 Function&lt;String,String&gt; 并对函数进行归约:

Function<String,String> combined = map.entrySet().stream()
        .reduce(
                Function.identity(),
                (f, e) -> x -> f.apply(x).replaceAll(e.getKey(), e.getValue()),
                Function::andThen
        );

return combined.apply(text);

【讨论】:

    【解决方案4】:

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

    您正在迭代一个可能没有指定迭代顺序的映射(如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();
    }
    

    从 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));
    

    你会得到

    bar, Bar, Baz
    

    证明替换 foo 优先于替换 f 并且其替换 bar 中的 b 未被替换。

    如果您想要再次替换替换中的匹配项,则情况会有所不同。在这种情况下,您将需要一种控制顺序的机制或实现重复替换,只有在没有匹配项时才会返回。当然,后者需要注意提供替换,这些替换总是最终会收敛到一个结果。

    例如

    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();
    }
    
    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));
    
    fx3x3, bx321r, bx321z
    

    【讨论】:

      猜你喜欢
      • 2015-07-07
      • 1970-01-01
      • 2015-08-29
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 2014-11-12
      • 2020-09-20
      相关资源
      最近更新 更多