如何在 Java 8 中映射映射中的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23213891/
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
How to map values in a map in Java 8?
提问by siledh
Say I have a Map<String, Integer>
. Is there an easy way to get a Map<String, String>
from it?
说我有一个Map<String, Integer>
. 有没有一种简单的方法可以从中获取Map<String, String>
?
By easy, I mean not like this:
简单,我的意思不是这样:
Map<String, String> mapped = new HashMap<>();
for(String key : originalMap.keySet()) {
mapped.put(key, originalMap.get(key).toString());
}
But rather some one liner like:
而是一些像这样的班轮:
Map<String, String> mapped = originalMap.mapValues(v -> v.toString());
But obviously there is no method mapValues
.
但显然没有办法mapValues
。
采纳答案by assylias
You need to stream the entries and collect them in a new map:
您需要流式传输条目并将它们收集在新地图中:
Map<String, String> result = map.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, e -> String.valueOf(e.getValue()));
回答by skiwi
The easiest way to do so is:
最简单的方法是:
Map<String, Integer> map = new HashMap<>();
Map<String, String> mapped = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue())));
What you do here, is:
你在这里做的是:
- Obtain a
Stream<Map.Entry<String, Integer>>
- Collect the results in the resulting map:
- Map the entries to their key.
- Map the entries to the new values, incorporating
String.valueOf
.
- 获得一个
Stream<Map.Entry<String, Integer>>
- 在生成的地图中收集结果:
- 将条目映射到它们的键。
- 将条目映射到新值,将
String.valueOf
.
The reason you cannot do it in a one-liner, is because the Map
interface does not offer such, the closest you can get to that is map.replaceAll
, but that method dictates that the type should remain the same.
您不能在单行中执行此操作的原因是因为该Map
接口不提供此类,您可以获得的最接近的是map.replaceAll
,但该方法规定类型应保持不变。