Java 8: changing values of stream EntrySet
I have the following setup:
Map<Instant, String> items;
...
String renderTags(String text) {
// Renders markup tags in a string to human readable form
}
...
<?> getItems() {
// Here is where I need help
}
My problem is that the strings that are map values items
are tagged. I want to be able to getItems()
return all elements, but with syntax strings using the method renderTags(String)
. Something like:
// Doesn't work
items.entrySet().stream().map(e -> e.setValue(renderTags(e.getValue())));
What's the most efficient way to do this?
source to share
If you want to modify an existing map instead of generating a new one (like in your example), there is no need to use this stream at all. Use Map.replaceAll
:
items.replaceAll((k, v) -> renderTags(v));
return items;
If you want to keep the original map intact, please refer to the other answers.
source to share
You can try this with Collectors.toMap()
:
Map<Instant, String> getItems() {
return items.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> renderTags(entry.getValue())
));
}
By the way, if the name just says "get", you shouldn't convert it at all. The getter can be expected to be simple and inexpensive.
source to share
An alternative could be
Map<Instant, String> getItems() {
return items.entrySet().stream()
.peek(entry -> entry.setValue(renderTags(entry.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey,e -> e.getValue()));
}
Useful if you need to perform updates on the stream before calling the collector.
source to share