Java 8:更改 EntrySet 流的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31131984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:09:25  来源:igfitidea点击:

Java 8: Change the values of an EntrySet stream

javadictionaryjava-8java-stream

提问by Ruckus T-Boom

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 itemsmap 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:

我的问题是,作为items地图值的字符串用标签标记。我想getItems()返回所有项目,但使用该renderTags(String)方法解析的字符串。就像是:

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

What is the most effective way to do this?

做到这一点最有效的方法是什么?

回答by Didier L

If you want a Mapas result:

如果你想要一个Map结果:

Map<Instant, String> getItems() {
    return items.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    e -> renderTags(e.getValue())));
}

回答by Tagir Valeev

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:

如果您想修改现有地图而不是生成新地图(如您的示例中所示),则根本不需要使用流。使用Map.replaceAll

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

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

如果您想保持原始地图不变,请参阅其他答案。

回答by Vlasec

You can try it this way with Collectors.toMap():

您可以通过以下方式尝试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 says simply "get", you shouldn't generally transform it in there. One expects a getter to be simple and not costy at all.

顺便说一句,如果名称只是简单地表示“get”,则通常不应将其转换到那里。人们期望 getter 简单且根本不昂贵。

回答by Max

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 have to perform updates on the stream before collect call.

如果您必须在对方付费电话之前对流执行更新,则很有用。