gpt4 book ai didi

java - 使用 Java Stream API 将 Map> 中的类型 X 转换为 Y

转载 作者:太空狗 更新时间:2023-10-29 22:37:03 24 4
gpt4 key购买 nike

我想从 map 的 map 转换内部 map 。

旧 map :Map<String, Map<LocalDate, Integer>>整数表示秒

新 map :Map<String, Map<LocalDate, Duration>>

我尝试创建新的内部 map ,但出现错误

Error: java: no suitable method found for putAll(java.util.stream.Stream<java.lang.Object>) method java.util.Map.putAll(java.util.Map<? extends java.time.LocalDate,? extends java.time.Duration>) is not applicable

oldMap.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> new HashMap<LocalDate, Duration>() {{
putAll(
e.getValue().entrySet().stream()
.map(x -> new HashMap.SimpleEntry<LocalDate, Duration>
(x.getKey(), Duration.ofSeconds(x.getValue())))
);
}}
));

最佳答案

如果你想要紧凑的代码,你可以使用

Map<String, Map<LocalDate, Duration>> newMap = new HashMap<>();
oldMap.forEach((s,o) -> o.forEach((d, i) ->
newMap.computeIfAbsent(s, x->new HashMap<>()).put(d, Duration.ofSeconds(i))));

如果想避免不必要的散列运算,可以稍微扩展一下

Map<String, Map<LocalDate, Duration>> newMap = new HashMap<>();
oldMap.forEach((s,o) -> {
Map<LocalDate, Duration> n = new HashMap<>();
newMap.put(s, n);
o.forEach((d, i) -> n.put(d, Duration.ofSeconds(i)));
});

关于java - 使用 Java Stream API 将 Map<K, Map<V, X>> 中的类型 X 转换为 Y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44283257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com