Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Change the values of an EntrySet stream

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 problems is, the strings that are the values of the items map are marked up with tags. I want getItems() to return all the items, but with the strings parsed using the renderTags(String) method. Something like:

// Doesn't work
items.entrySet().stream().map(e -> e.setValue(renderTags(e.getValue())));

What is the most effective way to do this?

like image 733
Ruckus T-Boom Avatar asked Jun 30 '15 07:06

Ruckus T-Boom


2 Answers

If you want a Map as result:

Map<Instant, String> getItems() {
    return items.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    e -> renderTags(e.getValue())));
}
like image 156
Didier L Avatar answered Oct 28 '22 18:10

Didier L


If you want to modify an existing map instead of generating the new one (as in your example), there's no need to use the stream at all. Use Map.replaceAll:

items.replaceAll((k, v) -> renderTags(v));
return items;

If you want to keep the original map unchanged, consult other answers.

like image 42
Tagir Valeev Avatar answered Oct 28 '22 19:10

Tagir Valeev