【发布时间】:2016-07-10 09:49:28
【问题描述】:
我有String 和HashMap 如下代码:
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 的正文中重新分配。
那么有没有使用 Java 8 Stream API 将 String 替换为 HashMap 的解决方案?
【问题讨论】:
-
forEach()未同步。您的代码无法编译,因为您不能从 lambda 表达式内部对message产生副作用。即使你可以,你得到的只是message包含test上最后一个地图条目的最后一个替换。这可能不是你想要的。还因为“最后一个地图条目”对于HashMap是不确定的。 -
好的,谢谢,我知道了。但是我应该怎么做才能获得已经替换的所有测试内容?
标签: java hashmap java-8 java-stream