使用java 8流将字符串替换为哈希图值 [英] Replace String With hashmap value using java 8 stream
问题描述
我有 String
和 HashMap
如下代码:
I have String
and HashMap
like below codes:
Map<String, String> map = new HashMap<>();
map.put("ABC", "123");
String test = "helloABC";
map.forEach((key, value) -> {
test = test.replaceAll(key, value);
});
我尝试用 HashMap
值替换字符串,但这不起作用,因为 test
是最终的,不能在 的正文中重新分配forEach
.
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
.
那么有没有使用 Java 8 Stream API 将 String
替换为 HashMap
的解决方案?
So are there any solutions to replace String
with HashMap
using Java 8 Stream API?
推荐答案
由于仅使用 forEach()
无法做到这一点(message
必须是有效的 final),解决方法可能是创建一个最终容器(例如 List
),它存储一个被重写的 String
:
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<String> msg = Arrays.asList("helloABC");
map.forEach((key, value) -> msg.set(0, msg.get(0).replace(key, value)));
String test = msg.get(0);
请注意,我将 replaceAll()
更改为 replace()
因为前者适用于正则表达式,但从您的代码来看,您似乎需要替换为字符串本身(不用担心,尽管名称令人困惑,但它也会替换 所有 次出现).
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).
如果您想要确切的 Stream API,您可以使用 reduce()
操作:
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).
这篇关于使用java 8流将字符串替换为哈希图值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!