创建一个使用给定列表中的键初始化的映射。

huangapple go评论65阅读模式
英文:

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&lt;String&gt; entries I would like to create a HashMap&lt;String, Deque&lt;Instant&gt;&gt; map with keys being those from entries list.

I could do

for(String s: entries){map.put(s, new Deque&lt;&gt;()} however I'm looking for more elegant solution.

map = Stream.of(entries).collect(Collectors.toMap(x -&gt; (String) x, new Deque&lt;&gt;()));

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&lt;String, Deque&lt;Instant&gt;&gt; map = entries.stream()
        .collect(Collectors.toMap(x -&gt; x, x -&gt; new ArrayDeque&lt;&gt;()));

You can even replace x -&gt; x by Function.identity():

.collect(Collectors.toMap(Function.identity(), x -&gt; new ArrayDeque&lt;&gt;()));

huangapple
  • 本文由 发表于 2020年10月19日 17:09:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64424316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定