How to add an element to an ArrayList in a HashMap

How to add an element to an ArrayList in a HashMap?

    HashMap<String, ArrayList<Item>> Items = new HashMap<String, ArrayList<Item>>();
+5
source share
3 answers
HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();

public synchronized void addToList(String mapKey, Item myItem) {
    List<Item> itemsList = items.get(mapKey);

    // if list does not exist create it
    if(itemsList == null) {
         itemsList = new ArrayList<Item>();
         itemsList.add(myItem);
         items.put(mapKey, itemsList);
    } else {
        // add if item is not already in list
        if(!itemsList.contains(myItem)) itemsList.add(myItem);
    }
}
+18
source

First you need to add an ArrayList to the map

ArrayList<Item> al = new ArrayList<Item>();

Items.add("theKey", al); 

then you can add an element to ArrayLIst, which is inside the Map, as follows:

Items.get("theKey").add(item);  // item is an object of type Item
+7
source

Typical code is to create an explicit method to add to the list and create an ArrayList on the fly when adding. Pay attention to synchronization, so the list is created only once!

@Override
public synchronized boolean addToList(String key, Item item) {
   Collection<Item> list = theMap.get(key);
   if (list == null)  {
      list = new ArrayList<Item>();  // or, if you prefer, some other List, a Set, etc...
      theMap.put(key, list );
   }

   return list.add(item);
}
+5
source

All Articles