首页 > 解决方案 > 将元素添加到 HashMap 中的 ArrayList

问题描述

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

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

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

标签: javahashmap

解决方案


// 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");

推荐阅读