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).