gpt4 book ai didi

java - 创建使用给定列表中的键初始化的 Map

转载 作者:行者123 更新时间:2023-12-04 08:44:00 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Java 8 List<V> into Map<K, V>

(22 个回答)


10 个月前关闭。




我有一个 list List<String> entries我想创建一个 HashMap<String, Deque<Instant>> map key 来自 entries列表。
我可以for(String s: entries){map.put(s, new Deque<>()}但是我正在寻找更优雅的解决方案。

map = Stream.of(entries).collect(Collectors.toMap(x -> (String) x, new Deque<>()));
但是我遇到了类型转换错误。这是可修复的,我可以从键列表中构建映射吗?

最佳答案

我认为你需要这个:

Map<String, Deque<Instant>> map = entries.stream()
.collect(Collectors.toMap(x -> x, x -> new ArrayDeque<>()));
您甚至可以替换 x -> x来自 Function.identity() :
.collect(Collectors.toMap(Function.identity(), x -> new ArrayDeque<>()));

关于java - 创建使用给定列表中的键初始化的 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64424316/

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