【问题标题】:Create Map initialized using keys in given List [duplicate]创建使用给定列表中的键初始化的地图[重复]
【发布时间】:2021-02-02 01:13:39
【问题描述】:

我有一个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<>()));

但是我得到了转换错误。这可以修复吗,我可以根据键列表构建地图吗?

【问题讨论】:

  • @Aman 你的解决方案将无法编译
  • entries.stream().collect(Collectors.toMap(Function.identity(), x -&gt; new ArrayDeque()))Collectors.toMap(Function.identity(), x -&gt; new LinkedList()) 应该没问题。 @YCF_L 是的,忘了x-&gt;

标签: java dictionary collections java-8 java-stream


【解决方案1】:

我认为你需要这个:

Map<String, Deque<Instant>> map = entries.stream()
        .collect(Collectors.toMap(x -> x, x -> new ArrayDeque<>()));

您甚至可以将x -&gt; x 替换为Function.identity()

.collect(Collectors.toMap(Function.identity(), x -> new ArrayDeque<>()));

【讨论】:

  • Function.identity() 是一个很好的数学参考,只是不确定程序员是否认为这是一个清晰的代码。谢谢。
猜你喜欢
  • 2013-10-16
  • 1970-01-01
  • 2011-12-26
  • 2015-09-25
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多