Since this cannot be done using only forEach() ( message should be effectively final), a workaround could be to create a final container (e.g. List ) that stores one String that is rewritten:
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);
Please note that I changed replaceAll() to replace() , because the former works with regular expression, but judging by your code, you need to replace the string (do not worry, despite the confusing name, it also replaces all occurrences).
If you want to use the Stream API, you can use reduce() :
String test = map.entrySet() .stream() .reduce("helloABC", (s, e) -> s.replace(e.getKey(), e.getValue()), (s1, s2) -> null);
But keep in mind that such a reduction will only work correctly in a sequential (not parallel) thread, where the combiner function is never called (thus, there can be any).
Alex salauyou
source share