Replace string using hashmap value using java 8 stream

I have String and HashMap as shown below:

 Map<String, String> map = new HashMap<>(); map.put("ABC", "123"); String test = "helloABC"; map.forEach((key, value) -> { test = test.replaceAll(key, value); }); 

and I'm trying to replace the string with HashMap values, but this does not work, because test is final and cannot be reassigned in the forEach body.

So, are there any solutions to replace String with HashMap using Java 8 Stream API?

+8
java hashmap java-8 java-stream
source share
2 answers

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

+3
source share

This problem is not suitable for Streams API. The current incarnation of Streams is mainly aimed 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 thread-based approach that you might find interesting is to reduce the functions, not the line:

 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); 
+3
source share

All Articles