使用java 8流将String替换为hashmap值
我有String
和HashMap
如下面的代码:
Map map = new HashMap(); map.put("ABC", "123"); String test = "helloABC"; map.forEach((key, value) -> { test = test.replaceAll(key, value); });
我尝试用HashMap
值替换字符串,但这不起作用,因为test
是最终的,不能在forEach
的主体中重新分配。
那么有没有使用Java 8 Stream API用HashMap
替换String
解决方案?
由于这不能只forEach()
( message
必须是有效的最终),解决方法可能是创建一个最终容器(例如List
),它存储一个重写的String
:
final List msg = Arrays.asList("helloABC"); map.forEach((key, value) -> msg.set(0, msg.get(0).replace(key, value))); String test = msg.get(0);
请注意,我将replaceAll()
更改为replace()
因为前者使用正则表达式,但是根据您的代码进行判断似乎需要用字符串本身替换(不要担心,尽管名称混乱,它也会替换所有出现的事件)。
如果您想要精确的Stream API,可以使用reduce()
操作:
String test = map.entrySet() .stream() .reduce("helloABC", (s, e) -> s.replace(e.getKey(), e.getValue()), (s1, s2) -> null);
但是要考虑到,这种减少只能在串行(非并行)流中正常工作,其中从不调用组合器函数(因此可以是任何)。
这种问题不适合Streams API。 Streams的当前版本主要针对可以并行的任务。 未来可能会添加对此类操作的支持(请参阅https://bugs.openjdk.java.net/browse/JDK-8133680 )。
您可能会觉得有趣的一种基于流的方法是减少函数而不是字符串:
Function combined = map.entrySet().stream() .reduce( Function.identity(), (f, e) -> s -> f.apply(s).replaceAll(e.getKey(), e.getValue()), Function::andThen ); String result = combined.apply(test);