【问题标题】:Java: How to convert a list to HashMap (key being the list) in one line [duplicate]Java:如何在一行中将列表转换为HashMap(键是列表)[重复]
【发布时间】:2020-01-05 13:11:47
【问题描述】:

我有一个字符串数组列表:

ArrayList<String> list = Arrays.asList("A", "B", "C", "D");

我想初始化一个映射HashMap&lt;String, List&lt;Integer&gt;&gt;,我的列表元素是键,一个空的整数列表是值。

当然有一种使用循环的方法,但我想知道是否有一种方法可以在一行中完成。在看到a similar question 中的问题和答案后,我知道这是可行的:

HashMap<String, List<Integer>> bigMap = ImmutableMap.<String, List<Integer>>builder()
.put("A", new ArrayList<Integer>)
.put("B", new ArrayList<Integer>)
.put("C", new ArrayList<Integer>)
.put("D", new ArrayList<Integer>)
.build();

但这仅适用于列表大小较小的场景。我如何使用流来做到这一点,就像another question中提到的方式一样?

【问题讨论】:

  • 您是否阅读了链接问题中的this answer?你能解释一下你上面的问题是什么吗?
  • @Naman 是的,但是这个答案给出了一个例子,它映射到值,而不是键,它使用函数 getKey 作为键,这与我所拥有的不同。
  • 您提出的问题是使用流,链接的答案分享了这样做的方法。在您的情况下,映射中的常量值作为值起作用,e -&gt; Collections.emptyList()。至少试一试吧。

标签: java list arraylist java-8 hashmap


【解决方案1】:

使用Collectors.toMap():

Map<String,List<Integer>> bigMap =
    list.stream()
        .collect(Collectors.toMap(Function.identity(),e-> new ArrayList<Integer>()));

【讨论】:

  • e -&gt; Collections.emptyList() 如果更好阅读的话。
  • @Naman 这将用不可变的空Lists 填充Map。如果 OP 不想向那些 Lists 添加元素,为什么要首先创建这个 Map
  • 我认为问题集中在示例代码ImmutableMap.&lt;String, List&lt;Integer&gt;&gt;builder 的不变性上。无论如何,您所说的对于实际用例来说是有道理的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 2017-05-09
  • 2021-08-30
  • 2012-03-23
  • 2021-05-02
  • 1970-01-01
相关资源
最近更新 更多