gpt4 book ai didi

HashMap 上的 Java 8 Map Reduce 作为 lambda

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:36:40 24 4
gpt4 key购买 nike

我有一个 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(...); 但无法正常工作。

提前致谢。

最佳答案

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

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

关于HashMap 上的 Java 8 Map Reduce 作为 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50733080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com