java8 hashmap lambda,Java 8将HashMap上的Map减少为lambda

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

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

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

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

private static String replace(String text, Map 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 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并且替换f中的b不会被替换.

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

例如.

private static String replaceRepeatedly(String text, Map 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 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值