【问题标题】:Add Elements to an ArrayList within a HashMap [duplicate]将元素添加到 HashMap 中的 ArrayList [重复]
【发布时间】:2019-02-13 12:49:29
【问题描述】:

如何将元素添加到 HashMap 中的 ArrayList?

这是一个问题,我问了自己很多次,解决后忘记了。我想很多人都有相同的,所以这里是简单的答案。

// Example
HashMap<String, ArrayList<String>> someElements = new HashMap<String, ArrayList<String>>();

【问题讨论】:

  • 使用get获取值。然后使用add 将一个元素添加到列表中。 map.get(key).add(entry);。显然,您首先需要在其中放置一个实际列表。 map.put(key, new ArrayList&lt;&gt;());.
  • 请注意,还有一种方便的方法可以一步完成:map.computeIfAbsent(key, k -&gt; new ArrayList&lt;&gt;()).add(value);

标签: java hashmap


【解决方案1】:
// fill the HashMap with the key that you need
// initiate it with an empty ArrayList        
   someElements.put("keyString" , new ArrayList<String>());

// Later when wanting to add an element to the ArrayList of a key use
   someElements.get("keyString").add("TheStringValue");

【讨论】:

  • @funkyjelly 如果还没有涉及到,建议在 SO 上提问。因此,如果我们不决定将其作为重复项或其他原因关闭,则此答案是完全有效的,并且 SO 规则鼓励 OP 行为。
  • 但即便如此,这仅意味着该问题应该被否决,而不是答案。
  • @Zabuza 同意并且没有投反对票。已删除评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 2021-02-22
  • 1970-01-01
相关资源
最近更新 更多