英文:
Create Map initialized using keys in given List
问题
我有一个列表 List<String> entries
,我想要创建一个 HashMap<String, Deque<Instant>> map
,其中键是来自 entries
列表的值。
我可以这样做:
for(String s: entries){
map.put(s, new Deque<>());
}
然而,我正在寻找更优雅的解决方案。
map = Stream.of(entries).collect(Collectors.toMap(x -> (String) x, new Deque<>()));
然而,我遇到了类型转换错误。这个问题能修复吗?我能否从键的列表构造一个映射?
英文:
I have a list List<String> entries
I would like to create a HashMap<String, Deque<Instant>> map
with keys being those from entries
list.
I could do
for(String s: entries){map.put(s, new Deque<>()}
however I'm looking for more elegant solution.
map = Stream.of(entries).collect(Collectors.toMap(x -> (String) x, new Deque<>()));
however I get casting error. Is that fixable, can I constuct a map from list of keys?
答案1
得分: 2
我认为你需要这个:
Map<String, Deque<Instant>> map = entries.stream()
.collect(Collectors.toMap(x -> x, x -> new ArrayDeque<>()));
你甚至可以用 Function.identity()
替换 x -> x
:
.collect(Collectors.toMap(Function.identity(), x -> new ArrayDeque<>()));
英文:
I think you need this:
Map<String, Deque<Instant>> map = entries.stream()
.collect(Collectors.toMap(x -> x, x -> new ArrayDeque<>()));
You can even replace x -> x
by Function.identity()
:
.collect(Collectors.toMap(Function.identity(), x -> new ArrayDeque<>()));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论