Reputation: 135
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);
});
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?
Upvotes: 11
Views: 9561
Reputation: 14338
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);
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).
Upvotes: 7
Reputation: 28133
This sort of a problem is not well-suited for Streams API. The current incarnation of Streams is mainly directed at tasks that can be made parallel. Perhaps support for this type of operation will be added in the future (see https://bugs.openjdk.java.net/browse/JDK-8133680).
One streams-based approach that you might find interesting is to reduce on functions rather than on the string:
Function<String, String> 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);
Upvotes: 4