Java8: HashMaplt;X, Ygt; to HashMaplt;X, Zgt; using Stream / Map-Reduce / Collector(Java8:哈希映射lt;X,Ygt;到HashMaplt;X,Zgt;使用 Stream/Map-Reduce/Collector)
问题描述
我知道如何转变";Y
的简单 Java List
->Z
,即:
I know how to "transform" a simple Java List
from Y
-> Z
, i.e.:
List<String> x;
List<Integer> y = x.stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.toList());
现在我想对地图做基本相同的事情,即:
Now I'd like to do basically the same with a Map, i.e.:
INPUT:
{
"key1" -> "41", // "41" and "42"
"key2" -> "42" // are Strings
}
OUTPUT:
{
"key1" -> 41, // 41 and 42
"key2" -> 42 // are Integers
}
解决方案不应仅限于String
->整数
.就像上面的 List
示例一样,我想调用任何方法(或构造函数).
The solution should not be limited to String
-> Integer
. Just like in the List
example above, I'd like to call any method (or constructor).
推荐答案
Map<String, String> x;
Map<String, Integer> y =
x.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> Integer.parseInt(e.getValue())
));
它不如列表代码那么好.您不能在 map()
调用中构造新的 Map.Entry
,因此工作会混入 collect()
调用中.
It's not quite as nice as the list code. You can't construct new Map.Entry
s in a map()
call so the work is mixed into the collect()
call.
这篇关于Java8:哈希映射<X,Y>到HashMap<X,Z>使用 Stream/Map-Reduce/Collector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java8:哈希映射<X,Y>到HashMap<X,Z>使用 Stream/Map-Reduce/Collector


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01