java map 替换 value,使用java 8流替换String与hashmap值

I have String and HashMap like below codes:

Map map = new HashMap<>();

map.put("ABC", "123");

String test = "helloABC";

map.forEach((key, value) -> {

test = test.replaceAll(key, value);

});

and I try to replace the string with the HashMap values, but this doesn't work because test is final and cannot be reassigned in the body of forEach.

So are there any solutions to replace String with HashMap using Java 8 Stream API?

解决方案

As this cannot be made using only forEach() (message must be effectively final), workaround could be to create a final container (e. g. List) which stores a single String that is re-written:

final List msg = Arrays.asList("helloABC");

map.forEach((key, value) -> msg.set(0, msg.get(0).replace(key, value)));

String test = msg.get(0);

Note that I changed replaceAll() to replace() because former works with regex, but judging by your code seems you need replacement by string itself (don't worry, despite of confusing name it also replaces all occurrences).

If you want exactly Stream API, you may use reduce() operation:

String test = map.entrySet()

.stream()

.reduce("helloABC",

(s, e) -> s.replace(e.getKey(), e.getValue()),

(s1, s2) -> null);

But take into account, that such reduction will work properly only in serial (not parallel) stream, where combiner function is never called (thus may be any).

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值